From b7abeeac62906e926514fbb5c3f1bce886483f41 Mon Sep 17 00:00:00 2001 From: tellsense Date: Sat, 4 May 2024 17:55:29 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=BE=D1=87=D1=82=D0=B8=20=D0=B3=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SushiBar/SushiBarBusinessLogic/OrderLogic.cs | 240 ++++++++++-------- .../SushiBarBusinessLogic/WorkModeling.cs | 139 ++++++++++ .../BindingModels/OrderBindingModel.cs | 3 +- .../BusinessLogicsContracts/IWorkProcess.cs | 7 + .../SearchModels/OrderSearchModel.cs | 9 +- .../Controllers/ImplementerController.cs | 108 ++++++++ .../SushiBarView/FormImplementer.Designer.cs | 3 + SushiBar/SushiBarView/FormImplementer.cs | 87 ++++++- .../SushiBarView/FormImplementers.Designer.cs | 27 +- SushiBar/SushiBarView/FormImplementers.cs | 102 +++++++- SushiBar/SushiBarView/FormMain.Designer.cs | 32 ++- SushiBar/SushiBarView/FormMain.cs | 18 +- 12 files changed, 643 insertions(+), 132 deletions(-) create mode 100644 SushiBar/SushiBarBusinessLogic/WorkModeling.cs create mode 100644 SushiBar/SushiBarContracts/BusinessLogicsContracts/IWorkProcess.cs create mode 100644 SushiBar/SushiBarRestApi/Controllers/ImplementerController.cs diff --git a/SushiBar/SushiBarBusinessLogic/OrderLogic.cs b/SushiBar/SushiBarBusinessLogic/OrderLogic.cs index bd1e895..8134ca4 100644 --- a/SushiBar/SushiBarBusinessLogic/OrderLogic.cs +++ b/SushiBar/SushiBarBusinessLogic/OrderLogic.cs @@ -13,113 +13,145 @@ using System.Threading.Tasks; namespace SushiBarBusinessLogic.BusinessLogics { - public class OrderLogic : IOrderLogic - { - private readonly ILogger _logger; - private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; - _orderStorage = orderStorage; - } - public List? ReadList(OrderSearchModel? model) - { - _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); - var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } - public bool CreateOrder(OrderBindingModel model) - { - CheckModel(model); - if (model.Status != OrderStatus.Неизвестен) - return false; - model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + public class OrderLogic : IOrderLogic + { + private readonly ILogger _logger; + private readonly IOrderStorage _orderStorage; + static readonly object _locker = new object(); + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } - public bool TakeOrderInWork(OrderBindingModel model) - { - return ChangeStatus(model, OrderStatus.Выполняется); - } + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, model.Id); + var element = _orderStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } - public bool FinishOrder(OrderBindingModel model) - { - return ChangeStatus(model, OrderStatus.Готов); - } + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } - public bool DeliveryOrder(OrderBindingModel model) - { - return ChangeStatus(model, OrderStatus.Выдан); - } + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) + return false; + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } - private void CheckModel(OrderBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (model.Count <= 0) - { - throw new ArgumentException("Колличество суши в заказе не может быть меньше 1", nameof(model.Count)); - } - if (model.Sum <= 0) - { - throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); - } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); - } - _logger.LogInformation("Sushi. SushiId:{SushiId}.Count:{Count}.Sum:{Sum}Id:{Id}", - model.SushiId, model.Count, model.Sum, model.Id); - } + public bool TakeOrderInWork(OrderBindingModel model) + { + lock (_locker) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } + } - private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } - model.DateCreate = element.DateCreate; - model.SushiId = element.SushiId; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - if (requiredStatus - model.Status == 1) - { - model.Status = requiredStatus; - if (model.Status == OrderStatus.Выдан) - model.DateImplement = DateTime.Now; - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); - throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); - } - } + public bool FinishOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Готов); + } + + public bool DeliveryOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выдан); + } + + private void CheckModel(OrderBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (model.Count <= 0) + { + throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); + } + if (model.Sum <= 0) + { + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + } + if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) + { + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + } + _logger.LogInformation("Sushi. SushiId:{SushiId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.SushiId, model.Count, model.Sum, model.Id); + } + + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) + { + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new InvalidOperationException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.SushiId = element.SushiId; + model.DateImplement = element.DateImplement; + model.ClientId = element.ClientId; + if (!model.ImplementerId.HasValue) + { + model.ImplementerId = element.ImplementerId; + } + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Готов) + { + model.DateImplement = DateTime.Now; + } + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + } + } } diff --git a/SushiBar/SushiBarBusinessLogic/WorkModeling.cs b/SushiBar/SushiBarBusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..7d1dc4f --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic/WorkModeling.cs @@ -0,0 +1,139 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModels; +using SushiBarContracts.ViewModels; +using SushiBarDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarBusinessLogic +{ + public class WorkModeling : IWorkProcess + { + private readonly ILogger _logger; + + private readonly Random _rnd; + + private IOrderLogic? _orderLogic; + + public WorkModeling(ILogger logger) + { + _logger = logger; + _rnd = new Random(1000); + } + + public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) + { + _orderLogic = orderLogic; + var implementers = implementerLogic.ReadList(null); + if (implementers == null) + { + _logger.LogWarning("DoWork. Implementers is null"); + return; + } + var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят }); + if (orders == null || orders.Count == 0) + { + _logger.LogWarning("DoWork. Orders is null or empty"); + return; + } + _logger.LogDebug("DoWork for {Count} orders", orders.Count); + foreach (var implementer in implementers) + { + Task.Run(() => WorkerWorkAsync(implementer, orders)); + } + } + + private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) + { + if (_orderLogic == null || implementer == null) + { + return; + } + await RunOrderInWork(implementer); + + await Task.Run(() => + { + foreach (var order in orders) + { + try + { + _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); + // пытаемся назначить заказ на исполнителя + _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = order.Id, + ImplementerId = implementer.Id + }); + // делаем работу + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = order.Id + }); + } + // кто-то мог уже перехватить заказ, игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // заканчиваем выполнение имитации в случае иной ошибки + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + }); + } + + private async Task RunOrderInWork(ImplementerViewModel implementer) + { + if (_orderLogic == null || implementer == null) + { + return; + } + try + { + var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel + { + ImplementerId = implementer.Id, + Status = OrderStatus.Выполняется + })); + if (runOrder == null) + { + return; + } + + _logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id); + // доделываем работу + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = runOrder.Id + }); + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + // заказа может не быть, просто игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + } +} diff --git a/SushiBar/SushiBarContracts/BindingModels/OrderBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/OrderBindingModel.cs index 779203c..e6a7365 100644 --- a/SushiBar/SushiBarContracts/BindingModels/OrderBindingModel.cs +++ b/SushiBar/SushiBarContracts/BindingModels/OrderBindingModel.cs @@ -13,7 +13,8 @@ namespace SushiBarContracts.BindingModels public int Id { get; set; } public int SushiId { get; set; } public int ClientId { get; set; } - public int Count { get; set; } + public int? ImplementerId { get; set; } + public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; set; } = DateTime.Now; diff --git a/SushiBar/SushiBarContracts/BusinessLogicsContracts/IWorkProcess.cs b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..fe5f271 --- /dev/null +++ b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,7 @@ +namespace SushiBarContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/SushiBar/SushiBarContracts/SearchModels/OrderSearchModel.cs b/SushiBar/SushiBarContracts/SearchModels/OrderSearchModel.cs index f2d4620..8d1a09a 100644 --- a/SushiBar/SushiBarContracts/SearchModels/OrderSearchModel.cs +++ b/SushiBar/SushiBarContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,5 @@ -using System; +using SushiBarDataModels.Enums; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -9,8 +10,10 @@ namespace SushiBarContracts.SearchModels public class OrderSearchModel { public int? Id { get; set; } - public int? ClientId { get; set; } - public DateTime? DateFrom { get; set; } + public OrderStatus? Status { get; set; } + public int? ClientId { get; set; } + public int? ImplementerId { get; set; } + public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } diff --git a/SushiBar/SushiBarRestApi/Controllers/ImplementerController.cs b/SushiBar/SushiBarRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..1974b92 --- /dev/null +++ b/SushiBar/SushiBarRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,108 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModels; +using SushiBarContracts.ViewModels; +using SushiBarDataModels.Enums; + +namespace SushiBarRestApi.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : Controller + { + private readonly ILogger _logger; + + private readonly IOrderLogic _order; + + private readonly IImplementerLogic _logic; + + public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger logger) + { + _logger = logger; + _order = order; + _logic = logic; + } + + [HttpGet] + public ImplementerViewModel? Login(string login, string password) + { + try + { + return _logic.ReadElement(new ImplementerSearchModel + { + ImplementerFIO = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка авторизации сотрудника"); + throw; + } + } + + [HttpGet] + public List? GetNewOrders() + { + try + { + return _order.ReadList(new OrderSearchModel + { + Status = OrderStatus.Принят + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения новых заказов"); + throw; + } + } + + [HttpGet] + public OrderViewModel? GetImplementerOrder(int implementerId) + { + try + { + return _order.ReadElement(new OrderSearchModel + { + ImplementerId = implementerId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); + throw; + } + } + + [HttpPost] + public void TakeOrderInWork(OrderBindingModel model) + { + try + { + _order.TakeOrderInWork(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id); + throw; + } + } + + [HttpPost] + public void FinishOrder(OrderBindingModel model) + { + try + { + _order.FinishOrder(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{Id}", model.Id); + throw; + } + } + } +} diff --git a/SushiBar/SushiBarView/FormImplementer.Designer.cs b/SushiBar/SushiBarView/FormImplementer.Designer.cs index 15664cd..fb27050 100644 --- a/SushiBar/SushiBarView/FormImplementer.Designer.cs +++ b/SushiBar/SushiBarView/FormImplementer.Designer.cs @@ -50,6 +50,7 @@ buttonCancel.TabIndex = 0; buttonCancel.Text = "Отмена"; buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; // // buttonSave // @@ -59,6 +60,7 @@ buttonSave.TabIndex = 1; buttonSave.Text = "Сохранить"; buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; // // labelFIO // @@ -141,6 +143,7 @@ Controls.Add(buttonCancel); Name = "FormImplementer"; Text = "Исполнитель"; + Load += FormImplementer_Load; ((System.ComponentModel.ISupportInitialize)numericUpDownExp).EndInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); ResumeLayout(false); diff --git a/SushiBar/SushiBarView/FormImplementer.cs b/SushiBar/SushiBarView/FormImplementer.cs index e048ccf..0f68c0b 100644 --- a/SushiBar/SushiBarView/FormImplementer.cs +++ b/SushiBar/SushiBarView/FormImplementer.cs @@ -1,4 +1,8 @@ -using System; +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModels; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,9 +16,88 @@ namespace SushiBarView { public partial class FormImplementer : Form { - public FormImplementer() + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + + public FormImplementer(ILogger logger, IImplementerLogic logic) { InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormImplementer_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + var view = _logic.ReadElement(new ImplementerSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxFIO.Text = view.ImplementerFIO; + textBoxPassword.Text = view.Password; + numericUpDownExp.Value = view.WorkExperience; + numericUpDownQualification.Value = view.Qualification; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxPassword.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFIO.Text, + Password = textBoxPassword.Text, + WorkExperience = (int)numericUpDownExp.Value, + Qualification = (int)numericUpDownQualification.Value + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при создании или обновлении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); } } } diff --git a/SushiBar/SushiBarView/FormImplementers.Designer.cs b/SushiBar/SushiBarView/FormImplementers.Designer.cs index 78a0f18..a686d6b 100644 --- a/SushiBar/SushiBarView/FormImplementers.Designer.cs +++ b/SushiBar/SushiBarView/FormImplementers.Designer.cs @@ -28,21 +28,21 @@ /// private void InitializeComponent() { - dataGridView1 = new DataGridView(); + dataGridView = new DataGridView(); buttonAdd = new Button(); buttonUpd = new Button(); buttonDel = new Button(); buttonRef = new Button(); - ((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // - // dataGridView1 + // dataGridView // - dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView1.Location = new Point(2, 3); - dataGridView1.Name = "dataGridView1"; - dataGridView1.Size = new Size(469, 405); - dataGridView1.TabIndex = 0; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(2, 3); + dataGridView.Name = "dataGridView"; + dataGridView.Size = new Size(469, 405); + dataGridView.TabIndex = 0; // // buttonAdd // @@ -52,6 +52,7 @@ buttonAdd.TabIndex = 1; buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; // // buttonUpd // @@ -61,6 +62,7 @@ buttonUpd.TabIndex = 2; buttonUpd.Text = "Изменить"; buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += buttonUpd_Click; // // buttonDel // @@ -70,6 +72,7 @@ buttonDel.TabIndex = 3; buttonDel.Text = "Удалить"; buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += buttonDel_Click; // // buttonRef // @@ -79,6 +82,7 @@ buttonRef.TabIndex = 4; buttonRef.Text = "Обновить"; buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += buttonRef_Click; // // FormImplementers // @@ -89,16 +93,17 @@ Controls.Add(buttonDel); Controls.Add(buttonUpd); Controls.Add(buttonAdd); - Controls.Add(dataGridView1); + Controls.Add(dataGridView); Name = "FormImplementers"; Text = "Исполнители"; - ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); + Load += FormImplementers_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); } #endregion - private DataGridView dataGridView1; + private DataGridView dataGridView; private Button buttonAdd; private Button buttonUpd; private Button buttonDel; diff --git a/SushiBar/SushiBarView/FormImplementers.cs b/SushiBar/SushiBarView/FormImplementers.cs index bd88f26..0a0e121 100644 --- a/SushiBar/SushiBarView/FormImplementers.cs +++ b/SushiBar/SushiBarView/FormImplementers.cs @@ -1,4 +1,8 @@ -using System; +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.ViewModels; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,9 +16,103 @@ namespace SushiBarView { public partial class FormImplementers : Form { - public FormImplementers() + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + + public FormImplementers(ILogger logger, IImplementerLogic implementerLogic) { InitializeComponent(); + _logger = logger; + _logic = implementerLogic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ImplementerFIO"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка исполнителей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void FormImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void buttonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void buttonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление исполнителя"); + try + { + if (!_logic.Delete(new ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); } } } diff --git a/SushiBar/SushiBarView/FormMain.Designer.cs b/SushiBar/SushiBarView/FormMain.Designer.cs index 6e8364f..3aa7df2 100644 --- a/SushiBar/SushiBarView/FormMain.Designer.cs +++ b/SushiBar/SushiBarView/FormMain.Designer.cs @@ -38,11 +38,13 @@ toolStripMenuItem = new ToolStripMenuItem(); componentsToolStripMenuItem = new ToolStripMenuItem(); sushiToolStripMenuItem = new ToolStripMenuItem(); + clientToolStripMenuItem = new ToolStripMenuItem(); ReportsToolStripMenuItem = new ToolStripMenuItem(); ComponentsListToolStripMenuItem = new ToolStripMenuItem(); ComponentSushisToolStripMenuItem = new ToolStripMenuItem(); OrdersToolStripMenuItem = new ToolStripMenuItem(); - clientToolStripMenuItem = new ToolStripMenuItem(); + startWorkToolStripMenuItem = new ToolStripMenuItem(); + employersToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -108,7 +110,7 @@ // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, ReportsToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, ReportsToolStripMenuItem, startWorkToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(1265, 24); @@ -117,7 +119,7 @@ // // toolStripMenuItem // - toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, sushiToolStripMenuItem, clientToolStripMenuItem }); + toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, sushiToolStripMenuItem, clientToolStripMenuItem, employersToolStripMenuItem }); toolStripMenuItem.Name = "toolStripMenuItem"; toolStripMenuItem.Size = new Size(94, 20); toolStripMenuItem.Text = "Справочники"; @@ -136,6 +138,13 @@ sushiToolStripMenuItem.Text = "Суши"; sushiToolStripMenuItem.Click += sushiToolStripMenuItem_Click; // + // clientToolStripMenuItem + // + clientToolStripMenuItem.Name = "clientToolStripMenuItem"; + clientToolStripMenuItem.Size = new Size(180, 22); + clientToolStripMenuItem.Text = "Клиент"; + clientToolStripMenuItem.Click += clientToolStripMenuItem_Click; + // // ReportsToolStripMenuItem // ReportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentsListToolStripMenuItem, ComponentSushisToolStripMenuItem, OrdersToolStripMenuItem }); @@ -164,12 +173,17 @@ OrdersToolStripMenuItem.Text = "Список заказов"; OrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; // - // clientToolStripMenuItem + // startWorkToolStripMenuItem // - clientToolStripMenuItem.Name = "clientToolStripMenuItem"; - clientToolStripMenuItem.Size = new Size(180, 22); - clientToolStripMenuItem.Text = "Клиент"; - clientToolStripMenuItem.Click += clientToolStripMenuItem_Click; + startWorkToolStripMenuItem.Name = "startWorkToolStripMenuItem"; + startWorkToolStripMenuItem.Size = new Size(92, 20); + startWorkToolStripMenuItem.Text = "Запуск работ"; + // + // employersToolStripMenuItem + // + employersToolStripMenuItem.Name = "employersToolStripMenuItem"; + employersToolStripMenuItem.Size = new Size(180, 22); + employersToolStripMenuItem.Text = "Исполнители"; // // FormMain // @@ -211,5 +225,7 @@ private ToolStripMenuItem ComponentSushisToolStripMenuItem; private ToolStripMenuItem OrdersToolStripMenuItem; private ToolStripMenuItem clientToolStripMenuItem; + private ToolStripMenuItem startWorkToolStripMenuItem; + private ToolStripMenuItem employersToolStripMenuItem; } } \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormMain.cs b/SushiBar/SushiBarView/FormMain.cs index 501992f..8dc3b72 100644 --- a/SushiBar/SushiBarView/FormMain.cs +++ b/SushiBar/SushiBarView/FormMain.cs @@ -19,12 +19,14 @@ namespace SushiBarView private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + private readonly IWorkProcess _workProcess; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; + _workProcess = workProcess; } private void FormMain_Load(object sender, EventArgs e) { @@ -205,5 +207,19 @@ e) form.ShowDialog(); } } + private void employersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } + + private void startWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } } }