почти все. сломалось

This commit is contained in:
MorozovDanil 2024-12-02 17:51:40 +04:00
parent bb69e427c8
commit f6e89b6040
6 changed files with 191 additions and 166 deletions

View File

@ -14,34 +14,22 @@ public class Order
public DateTime DateIssue { get; private set; } public DateTime DateIssue { get; private set; }
public int FullPrice { get; private set; } public int FullPrice { get; private set; }
public int MasterId { get; private set; } public int MasterId { get; private set; }
public List<OrderDetail> OrderDetails { get; private set; } public IEnumerable<OrderDetail> OrderDetails { get; private set; } = [];
private Order() public static Order CreateOperation(int id, int fullPrice, int masterId, DateTime dateCompletion,
DateTime dateIssue, IEnumerable<OrderDetail> orderDetails)
{ {
OrderDetails = new List<OrderDetail>();
}
public static Order CreateOperation(int id, int fullPrice, int masterId, DateTime dateCompletion, DateTime dateIssue)
{
if (dateCompletion > DateTime.Now || dateIssue > DateTime.Now)
{
throw new ArgumentException("Дата начала работы и дата завершения не могут быть в будущем.");
}
return new Order return new Order
{ {
Id = id, Id = id,
OrderDate = DateTime.Now, // Автоматически задается текущая дата OrderDate = DateTime.Now,
DateCompletion = dateCompletion, DateCompletion = dateCompletion,
DateIssue = dateIssue, DateIssue = dateIssue,
FullPrice = fullPrice, FullPrice = fullPrice,
MasterId = masterId MasterId = masterId,
OrderDetails = orderDetails
}; };
} }
public void AddOrderDetail(int detailId, int detailCount)
{
var orderDetail = OrderDetail.CreateOperation(this.Id, detailId, detailCount);
OrderDetails.Add(orderDetail);
}
} }

View File

@ -165,6 +165,7 @@
groupBox1.Size = new Size(401, 224); groupBox1.Size = new Size(401, 224);
groupBox1.TabIndex = 12; groupBox1.TabIndex = 12;
groupBox1.TabStop = false; groupBox1.TabStop = false;
groupBox1.Text = "Деталь";
// //
// dataGridView // dataGridView
// //
@ -183,7 +184,7 @@
// //
// Detail // Detail
// //
Detail.HeaderText = "Деталь"; Detail.HeaderText = "Название детали";
Detail.Name = "Detail"; Detail.Name = "Detail";
// //
// DetailCount // DetailCount

View File

@ -1,5 +1,7 @@
using ProjectRepairCompany.Entities; using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using ProjectRepairCompany.Repositories; using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.Metrics; using System.Diagnostics.Metrics;
@ -8,12 +10,11 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace ProjectRepairCompany.Forms namespace ProjectRepairCompany.Forms;
public partial class FormOrder : Form
{ {
public partial class FormOrder : Form
{
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly IDetailRepository _detailRepository;
private int? _orderId; private int? _orderId;
public int Id public int Id
@ -27,11 +28,13 @@ namespace ProjectRepairCompany.Forms
{ {
throw new InvalidOperationException(nameof(order)); throw new InvalidOperationException(nameof(order));
} }
numericUpDownFullPrice.Value = order.FullPrice;
comboBoxMaster.SelectedValue = order.MasterId; comboBoxMaster.SelectedValue = order.MasterId;
numericUpDownFullPrice.Value = (decimal)order.FullPrice;
dateTimeCompletion.Value = order.DateCompletion; dateTimeCompletion.Value = order.DateCompletion;
dateTimeIssue.Value = order.DateIssue; dateTimeIssue.Value = order.DateIssue;
dataGridView.Rows.Clear();
foreach (var detail in order.OrderDetails) foreach (var detail in order.OrderDetails)
{ {
dataGridView.Rows.Add(detail.DetailId, detail.DetailCount); dataGridView.Rows.Add(detail.DetailId, detail.DetailCount);
@ -42,6 +45,7 @@ namespace ProjectRepairCompany.Forms
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
} }
} }
} }
@ -51,13 +55,13 @@ namespace ProjectRepairCompany.Forms
InitializeComponent(); InitializeComponent();
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_detailRepository = detailRepository ?? throw new ArgumentNullException(nameof(detailRepository));
comboBoxMaster.DataSource = masterRepository.ReadMasters(); comboBoxMaster.DataSource = masterRepository.ReadMasters();
comboBoxMaster.DisplayMember = "MasterName"; comboBoxMaster.DisplayMember = "MasterName";
comboBoxMaster.ValueMember = "Id"; comboBoxMaster.ValueMember = "Id";
Detail.DataSource = _detailRepository.ReadDetails(); Detail.DataSource = detailRepository.ReadDetails();
Detail.DisplayMember = "NameDetail"; Detail.DisplayMember = "NameDetail";
Detail.ValueMember = "Id"; Detail.ValueMember = "Id";
} }
@ -71,19 +75,7 @@ namespace ProjectRepairCompany.Forms
throw new Exception("Имеются незаполненные поля."); throw new Exception("Имеются незаполненные поля.");
} }
var order = Order.CreateOperation(_orderId ?? 0, Convert.ToInt32(numericUpDownFullPrice.Value), var order = CreateOrder();
(int)comboBoxMaster.SelectedValue, dateTimeCompletion.Value, dateTimeIssue.Value);
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["Detail"].Value != null && row.Cells["DetailCount"].Value != null)
{
var detailId = (int)row.Cells["Detail"].Value;
var detailCount = (int)row.Cells["DetailCount"].Value;
order.AddOrderDetail(detailId, detailCount);
}
}
if (_orderId.HasValue) if (_orderId.HasValue)
{ {
_orderRepository.UpdateOrder(order); _orderRepository.UpdateOrder(order);
@ -92,7 +84,7 @@ namespace ProjectRepairCompany.Forms
{ {
_orderRepository.CreateOrder(order); _orderRepository.CreateOrder(order);
} }
DialogResult = DialogResult.OK;
Close(); Close();
} }
catch (Exception ex) catch (Exception ex)
@ -101,7 +93,38 @@ namespace ProjectRepairCompany.Forms
} }
} }
private void ButtonCancel_Click(object sender, EventArgs e) => Close(); private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<OrderDetail> CreateListOrderDetailsFromDataGrid()
{
var list = new List<OrderDetail>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["Detail"].Value == null ||
row.Cells["DetailCount"].Value == null)
{
continue;
} }
list.Add(OrderDetail.CreateOperation(0,
Convert.ToInt32(row.Cells["Detail"].Value),
Convert.ToInt32(row.Cells["DetailCount"].Value)));
}
return list;
}
private Order CreateOrder()
{
var orderDetails = CreateListOrderDetailsFromDataGrid();
return Order.CreateOperation(
_orderId ?? 0,
Convert.ToInt32(numericUpDownFullPrice.Value),
(int)comboBoxMaster.SelectedValue,
dateTimeCompletion.Value,
dateTimeIssue.Value,
orderDetails
);
}
} }

View File

@ -1,5 +1,6 @@
using ProjectRepairCompany.Entities; using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Repositories; using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -61,9 +62,14 @@ namespace ProjectRepairCompany.Forms
try try
{ {
var form = _container.Resolve<FormOrder>(); var form = _container.Resolve<FormOrder>();
form.Id = findId; form.Id = findId;
form.ShowDialog();
if (form.ShowDialog() == DialogResult.OK)
{
LoadList(); LoadList();
dataGridView.Refresh();
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -93,17 +99,8 @@ namespace ProjectRepairCompany.Forms
} }
} }
private void LoadList() private void LoadList() => dataGridView.DataSource =_orderRepository.ReadOrders();
{
try
{
dataGridView.DataSource = _orderRepository.ReadOrders();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool TryGetIdentifierFromSelectRow(out int id) private bool TryGetIdentifierFromSelectRow(out int id)
{ {

View File

@ -25,37 +25,49 @@ public class OrderRepository : IOrderRepository
} }
public void CreateOrder(Order order) public void CreateOrder(Order order)
{ {
_logger.LogInformation("Добавление объекта"); _logger.LogInformation("Добавление нового заказа.");
_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);
connection.Open(); connection.Open();
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
var queryInsert = @" var queryInsert = @"
INSERT INTO ""Order"" (OrderDate, DateCompletion, DateIssue, FullPrice, MasterId) INSERT INTO ""Order"" (OrderDate, DateCompletion, DateIssue, FullPrice, MasterId)
VALUES (@OrderDate, @DateCompletion, @DateIssue, @FullPrice, @MasterId); VALUES (@OrderDate, @DateCompletion, @DateIssue, @FullPrice, @MasterId)
SELECT MAX(Id) FROM ""Order"""; RETURNING Id";
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction); var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
_logger.LogInformation("Новый заказ создан с Id {OrderId}", orderId);
var querySubInsert = @" var querySubInsert = @"
INSERT INTO OrderDetail (OrderId, DetailId, DetailCount) INSERT INTO OrderDetail (OrderId, DetailId, DetailCount)
VALUES (@OrderId, @DetailId, @DetailCount)"; VALUES (@OrderId, @DetailId, @DetailCount)";
foreach (var elem in order.OrderDetails) foreach (var elem in order.OrderDetails)
{ {
connection.Execute(querySubInsert, new {orderId, elem.DetailId, elem.DetailCount}, transaction); _logger.LogDebug("Добавление детали: DetailId = {DetailId}, DetailCount = {DetailCount}",
elem.DetailId, elem.DetailCount);
connection.Execute(querySubInsert, new { orderId, elem.DetailId, elem.DetailCount }, transaction);
} }
transaction.Commit(); transaction.Commit();
_logger.LogInformation("Заказ с деталями успешно добавлен.");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка добавления"); _logger.LogError(ex, "Ошибка при добавлении заказа.");
throw; throw;
} }
} }
public void UpdateOrder(Order order) public void UpdateOrder(Order order)
{ {
_logger.LogInformation("Обновление объекта"); _logger.LogInformation("Обновление заказа с Id {OrderId}", order.Id);
_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);
@ -79,6 +91,8 @@ VALUES (@OrderId, @DetailId, @DetailCount)";
order.MasterId order.MasterId
}, transaction); }, transaction);
_logger.LogInformation("Заказ с Id {OrderId} обновлен.", order.Id);
var queryDeleteDetails = "DELETE FROM OrderDetail WHERE OrderId = @OrderId"; var queryDeleteDetails = "DELETE FROM OrderDetail WHERE OrderId = @OrderId";
connection.Execute(queryDeleteDetails, new { order.Id }, transaction); connection.Execute(queryDeleteDetails, new { order.Id }, transaction);
@ -97,13 +111,15 @@ VALUES (@OrderId, @DetailId, @DetailCount)";
} }
transaction.Commit(); transaction.Commit();
_logger.LogInformation("Детали для заказа с Id {OrderId} обновлены.", order.Id);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка при обновлении"); _logger.LogError(ex, "Ошибка при обновлении заказа с Id {OrderId}.", order.Id);
throw; throw;
} }
} }
public void DeleteOrder(int id) public void DeleteOrder(int id)