Лаб2 сделана

This commit is contained in:
Pyro 2024-12-25 00:24:24 +04:00
parent b0e19ce372
commit 015f034590
19 changed files with 259 additions and 82 deletions

View File

@ -1,4 +1,6 @@
namespace ProjectConfectioneryFactory.Entities;
using System.ComponentModel;
namespace ProjectConfectioneryFactory.Entities;
public class Order
{
@ -6,17 +8,30 @@ public class Order
public int ClientId { get; private set; }
public bool Completed { get; private set; }
public DateTime Date { get; private set; }
public string Products => OrderProducts != null ?
string.Join(", ", OrderProducts.Select(x => $"{x.ProductName} {x.Count}")) :
string.Empty;
[Browsable(false)]
public IEnumerable<OrderProduct> OrderProducts { get; private set; } = [];
public static Order CreateOperation(int id, int clientid, bool completed, IEnumerable<OrderProduct> orderProducts)
public static Order CreateOperation(int id, int clientid, bool completed, DateTime date, IEnumerable<OrderProduct> orderProducts)
{
return new Order
{
Id = id,
ClientId = clientid,
Completed = completed,
Date = DateTime.Now,
Date = date,
OrderProducts = orderProducts
};
}
public void SetOrderProducts(IEnumerable<OrderProduct> orderProducts)
{
if (orderProducts != null && orderProducts.Any())
{
OrderProducts = orderProducts;
}
}
}

View File

@ -4,6 +4,7 @@ public class OrderProduct
{
public int OrderId { get; private set; }
public int ProductId { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public int Count { get; private set; }
public static OrderProduct CreateEntity(int orderid, int productid, int count)

View File

@ -1,4 +1,5 @@
using ProjectConfectioneryFactory.Entities.Enums;
using System.ComponentModel;
namespace ProjectConfectioneryFactory.Entities;
@ -8,6 +9,11 @@ public class Product
public ConfectioneryType ConfectioneryType { get; private set; }
public string Name { get; private set; } = string.Empty;
public double Price { get; private set; }
public string Components => ProductComponents != null ?
string.Join(", ", ProductComponents.Select(x => $"{x.ComponentName} {x.Weight}")) :
string.Empty;
[Browsable(false)]
public IEnumerable<ProductComponent> ProductComponents { get; private set; } = [];
public static Product CreateEntity(int id, ConfectioneryType сonfectioneryType, string name, double price, IEnumerable<ProductComponent> productComponents)
@ -21,4 +27,12 @@ public class Product
ProductComponents = productComponents
};
}
public void SetProductComponents(IEnumerable<ProductComponent> productComponents)
{
if (productComponents != null && productComponents.Any())
{
ProductComponents = productComponents;
}
}
}

View File

@ -4,6 +4,7 @@ public class ProductComponent
{
public int ProductId { get; private set; }
public int ComponentId { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Weight { get; private set; }
public static ProductComponent CreateEntity(int productid, int componentid, double weight)

View File

@ -9,7 +9,7 @@ public class Supply
public bool Completed { get; private set; }
public DateTime Date { get; private set; }
public static Supply CreateOperation(int id, int supplierid, int componentid, double weight, bool completed)
public static Supply CreateOperation(int id, int supplierid, int componentid, double weight, bool completed, DateTime date)
{
return new Supply
{
@ -18,7 +18,7 @@ public class Supply
ComponentId = componentid,
Weight = weight,
Completed = completed,
Date = DateTime.Now
Date = date
};
}
}

View File

@ -52,7 +52,7 @@
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ClientsToolStripMenuItem, ProductsToolStripMenuItem, ComponentsToolStripMenuItem, SuppliersToolStripMenuItem });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ClientsToolStripMenuItem, ComponentsToolStripMenuItem, ProductsToolStripMenuItem, SuppliersToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
@ -95,14 +95,14 @@
// OrdersToolStripMenuItem
//
OrdersToolStripMenuItem.Name = "OrdersToolStripMenuItem";
OrdersToolStripMenuItem.Size = new Size(180, 22);
OrdersToolStripMenuItem.Size = new Size(126, 22);
OrdersToolStripMenuItem.Text = "Заказы";
OrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
//
// SupplysToolStripMenuItem
//
SupplysToolStripMenuItem.Name = "SupplysToolStripMenuItem";
SupplysToolStripMenuItem.Size = new Size(180, 22);
SupplysToolStripMenuItem.Size = new Size(126, 22);
SupplysToolStripMenuItem.Text = "Поставки";
SupplysToolStripMenuItem.Click += SupplysToolStripMenuItem_Click;
//

View File

@ -1,6 +1,5 @@
using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Repositories;
using System.Text.RegularExpressions;
namespace ProjectConfectioneryFactory.Forms
{

View File

@ -1,6 +1,5 @@
using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Repositories;
using ProjectConfectioneryFactory.Repositories.Implementations;
namespace ProjectConfectioneryFactory.Forms
{
@ -17,14 +16,26 @@ namespace ProjectConfectioneryFactory.Forms
try
{
var order = _orderRepository.ReadOrderById(value);
if (order == null)
{
throw new InvalidDataException(nameof(order));
}
checkBoxCompleted.Checked = order.Completed;
dateTimePickerOrderDate.Value = order.Date;
_orderId = value;
foreach (OrderProduct elem in order.OrderProducts)
{
dataGridViewProducts.Rows.Add(elem.ProductId, elem.Count.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
}
}
@ -61,15 +72,14 @@ namespace ProjectConfectioneryFactory.Forms
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<OrderProduct>CreateListOrderProductFromDataGrid()
private List<OrderProduct> CreateListOrderProductFromDataGrid(int id)
{
var list = new List<OrderProduct>();
foreach (DataGridViewRow row in dataGridViewProducts.Rows)
@ -79,16 +89,19 @@ namespace ProjectConfectioneryFactory.Forms
{
continue;
}
list.Add(OrderProduct.CreateEntity(0,
list.Add(OrderProduct.CreateEntity(
id,
Convert.ToInt32(row.Cells["ColumnProductName"].Value),
Convert.ToInt32(row.Cells["ColumnProductCount"].Value)));
}
return list;
}
private Order CreateOrder(int id) => Order.CreateOperation(0,
private Order CreateOrder(int id) => Order.CreateOperation(
id,
(int)comboBoxClient.SelectedValue!,
checkBoxCompleted.Checked,
CreateListOrderProductFromDataGrid());
dateTimePickerOrderDate.Value,
CreateListOrderProductFromDataGrid(id));
}
}

View File

@ -17,10 +17,12 @@ namespace ProjectConfectioneryFactory.Forms
try
{
var product = _productRepository.ReadProductById(value);
if (product == null)
{
throw new InvalidDataException(nameof(product));
}
foreach (ConfectioneryType elem in Enum.GetValues(typeof(ConfectioneryType)))
{
if ((elem & product.ConfectioneryType) != 0)
@ -31,6 +33,11 @@ namespace ProjectConfectioneryFactory.Forms
textBoxProductName.Text = product.Name;
numericUpDownPrice.Value = (decimal)product.Price;
_productId = value;
foreach (ProductComponent elem in product.ProductComponents)
{
dataGridViewComponents.Rows.Add(elem.ComponentId, elem.Weight.ToString());
}
}
catch (Exception ex)
{
@ -81,7 +88,7 @@ namespace ProjectConfectioneryFactory.Forms
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<ProductComponent> CreateListProductComponentFromDataGrid()
private List<ProductComponent> CreateListProductComponentFromDataGrid(int id)
{
var list = new List<ProductComponent>();
foreach (DataGridViewRow row in dataGridViewComponents.Rows)
@ -91,7 +98,8 @@ namespace ProjectConfectioneryFactory.Forms
{
continue;
}
list.Add(ProductComponent.CreateEntity(0,
list.Add(ProductComponent.CreateEntity(
id,
Convert.ToInt32(row.Cells["ColumnComponent"].Value),
Convert.ToDouble(row.Cells["ColumnWeight"].Value)));
}
@ -110,7 +118,7 @@ namespace ProjectConfectioneryFactory.Forms
confectioneryType,
textBoxProductName.Text,
(double)numericUpDownPrice.Value,
CreateListProductComponentFromDataGrid());
CreateListProductComponentFromDataGrid(id));
}
}
}

View File

@ -28,7 +28,7 @@
/// </summary>
private void InitializeComponent()
{
dateTimePicker1 = new DateTimePicker();
dateTimePickerSupplyDate = new DateTimePicker();
label2 = new Label();
buttonCancel = new Button();
buttonSave = new Button();
@ -43,13 +43,13 @@
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
SuspendLayout();
//
// dateTimePicker1
// dateTimePickerSupplyDate
//
dateTimePicker1.Enabled = false;
dateTimePicker1.Location = new Point(108, 183);
dateTimePicker1.Name = "dateTimePicker1";
dateTimePicker1.Size = new Size(200, 23);
dateTimePicker1.TabIndex = 32;
dateTimePickerSupplyDate.Enabled = false;
dateTimePickerSupplyDate.Location = new Point(108, 183);
dateTimePickerSupplyDate.Name = "dateTimePickerSupplyDate";
dateTimePickerSupplyDate.Size = new Size(200, 23);
dateTimePickerSupplyDate.TabIndex = 32;
//
// label2
//
@ -164,7 +164,7 @@
Controls.Add(label5);
Controls.Add(comboBoxComponent);
Controls.Add(label3);
Controls.Add(dateTimePicker1);
Controls.Add(dateTimePickerSupplyDate);
Controls.Add(label2);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
@ -182,7 +182,7 @@
#endregion
private DateTimePicker dateTimePicker1;
private DateTimePicker dateTimePickerSupplyDate;
private Label label2;
private Button buttonCancel;
private Button buttonSave;

View File

@ -22,6 +22,7 @@ namespace ProjectConfectioneryFactory.Forms
}
numericUpDownWeight.Value = (decimal)supply.Weight;
checkBoxCompleted.Checked = supply.Completed;
dateTimePickerSupplyDate.Value = supply.Date;
_supplyId = value;
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
@ -73,6 +74,7 @@ namespace ProjectConfectioneryFactory.Forms
(int)comboBoxSupplier.SelectedValue!,
(int)comboBoxComponent.SelectedValue!,
Convert.ToDouble(numericUpDownWeight.Value),
checkBoxCompleted.Checked);
checkBoxCompleted.Checked,
dateTimePickerSupplyDate.Value);
}
}

View File

@ -1,10 +1,10 @@
using Unity.Lifetime;
using Unity;
using ProjectConfectioneryFactory.Repositories;
using ProjectConfectioneryFactory.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectConfectioneryFactory.Repositories;
using ProjectConfectioneryFactory.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace ProjectConfectioneryFactory

View File

@ -1,8 +1,8 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations;

View File

@ -66,18 +66,19 @@ public class OrderRepository : IOrderRepository
Completed=@Completed,
Date=@Date
WHERE Id=@Id";
var orderId = connection.QueryFirst<int>(queryUpdate, order, transaction);
connection.Execute(queryUpdate, order, transaction);
var querySubUpdate = @"
UPDATE OrderProducts
SET
OrderId=@OrderId,
ProductId=@ProductId,
Count=@Count
WHERE Id=@Id";
var querySubDelete = @"
DELETE FROM OrderProducts
WHERE OrderId=@Id";
connection.Execute(querySubDelete, order, transaction);
var querySubInsert = @"
INSERT INTO OrderProducts (OrderId, ProductId, Count)
VALUES (@OrderId, @ProductId, @Count)";
foreach (var elem in order.OrderProducts)
{
connection.Execute(querySubUpdate, new { orderId, elem.ProductId, elem.Count }, transaction);
connection.Execute(querySubInsert, elem, transaction);
}
transaction.Commit();
@ -115,12 +116,43 @@ public class OrderRepository : IOrderRepository
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Orders
WHERE Id=@id";
var order = connection.QueryFirst<Order>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(order));
return order;
SELECT
o.*,
op.OrderId,
op.ProductId,
p.Name AS ProductName,
op.Count
FROM Orders o
LEFT JOIN OrderProducts op ON op.OrderId = o.id
LEFT JOIN Products p ON p.id = op.productid
WHERE o.Id = @Id";
var productsDict = new Dictionary<int, List<OrderProduct>>();
var orders = connection.Query<Order, OrderProduct, Order>(querySelect,
(order, orderProduct) =>
{
if (!productsDict.TryGetValue(order.Id, out var pc))
{
pc = [];
productsDict.Add(order.Id, pc);
}
pc.Add(orderProduct);
return order;
},
new { id },
splitOn: "ProductId");
orders = productsDict.Select(x =>
{
var pc = orders.First(y => y.Id == x.Key);
pc.SetOrderProducts(x.Value);
return pc;
}).ToArray();
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(orders));
return orders.First();
}
catch (Exception ex)
{
@ -135,9 +167,40 @@ public class OrderRepository : IOrderRepository
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Orders";
var orders = connection.Query<Order>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
var querySelect = @"
SELECT
o.*,
op.OrderId,
op.ProductId,
p.Name AS ProductName,
op.Count
FROM Orders o
LEFT JOIN OrderProducts op ON op.OrderId = o.id
LEFT JOIN Products p ON p.id = op.productid";
var productsDict = new Dictionary<int, List<OrderProduct>>();
var orders = connection.Query<Order, OrderProduct, Order>(querySelect,
(order, orderProduct) =>
{
if (!productsDict.TryGetValue(order.Id, out var pc))
{
pc = [];
productsDict.Add(order.Id, pc);
}
pc.Add(orderProduct);
return order;
}, splitOn: "ProductId");
orders = productsDict.Select(x =>
{
var pc = orders.First(y => y.Id == x.Key);
pc.SetOrderProducts(x.Value);
return pc;
}).ToArray();
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)

View File

@ -1,10 +1,8 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Entities.Enums;
using Npgsql;
using System.Transactions;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
@ -68,18 +66,19 @@ public class ProductRepository : IProductRepository
Name=@Name,
Price=@Price
WHERE Id=@Id";
var productId = connection.QueryFirst<int>(queryUpdate, product, transaction);
connection.Execute(queryUpdate, product, transaction);
var querySubUpdate = @"
UPDATE ProductComponents
SET
ProductId=@ProductId,
ComponentId=@ComponentId,
Weight=@Weight
WHERE Id=@Id";
var querySubDelete = @"
DELETE FROM ProductComponents
WHERE ProductId=@Id";
connection.Execute(querySubDelete, product, transaction);
var querySubInsert = @"
INSERT INTO ProductComponents (ProductId, ComponentId, Weight)
VALUES (@ProductId, @ComponentId, @Weight)";
foreach (var elem in product.ProductComponents)
{
connection.Execute(querySubUpdate, new { productId, elem.ComponentId, elem.Weight }, transaction);
connection.Execute(querySubInsert, elem, transaction);
}
transaction.Commit();
}
@ -115,12 +114,43 @@ public class ProductRepository : IProductRepository
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Products
WHERE Id=@Id";
var product = connection.QueryFirst<Product>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
return product;
SELECT
p.*,
pc.ProductId,
pc.ComponentId,
c.Name AS ComponentName,
pc.Weight
FROM Products p
LEFT JOIN ProductComponents pc ON pc.productid = p.id
LEFT JOIN Components c ON c.id = pc.componentid
WHERE p.Id = @Id";
var componentsDict = new Dictionary<int, List<ProductComponent>>();
var products = connection.Query<Product, ProductComponent, Product>(querySelect,
(product, productComponent) =>
{
if (!componentsDict.TryGetValue(product.Id, out var pc))
{
pc = [];
componentsDict.Add(product.Id, pc);
}
pc.Add(productComponent);
return product;
},
new { id },
splitOn: "ProductId");
products = componentsDict.Select(x =>
{
var pc = products.First(y => y.Id == x.Key);
pc.SetProductComponents(x.Value);
return pc;
}).ToArray();
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(products));
return products.First();
}
catch (Exception ex)
{
@ -135,9 +165,40 @@ public class ProductRepository : IProductRepository
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Products";
var products = connection.Query<Product>(querySelect);
var querySelect = @"
SELECT
p.*,
pc.ProductId,
pc.ComponentId,
c.Name AS ComponentName,
pc.Weight
FROM Products p
LEFT JOIN ProductComponents pc ON pc.productid = p.id
LEFT JOIN Components c ON c.id = pc.componentid";
var componentsDict = new Dictionary<int, List<ProductComponent>>();
var products = connection.Query<Product, ProductComponent, Product>(querySelect,
(product, productComponent) =>
{
if (!componentsDict.TryGetValue(product.Id, out var pc))
{
pc = [];
componentsDict.Add(product.Id, pc);
}
pc.Add(productComponent);
return product;
}, splitOn: "ProductId");
products = componentsDict.Select(x =>
{
var pc = products.First(y => y.Id == x.Key);
pc.SetProductComponents(x.Value);
return pc;
}).ToArray();
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
return products;
}
catch (Exception ex)

View File

@ -1,8 +1,8 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations;

View File

@ -1,8 +1,8 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations;