From 062c43aacafa00b33f54d086c6eafb45586b7750 Mon Sep 17 00:00:00 2001 From: tellsense Date: Sat, 4 May 2024 18:40:09 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SushiBarBusinessLogic/WorkModeling.cs | 102 ++++++++++-------- SushiBar/SushiBarView/FormMain.Designer.cs | 38 ++----- SushiBar/SushiBarView/FormMain.cs | 52 --------- 3 files changed, 64 insertions(+), 128 deletions(-) diff --git a/SushiBar/SushiBarBusinessLogic/WorkModeling.cs b/SushiBar/SushiBarBusinessLogic/WorkModeling.cs index 7d1dc4f..a69285e 100644 --- a/SushiBar/SushiBarBusinessLogic/WorkModeling.cs +++ b/SushiBar/SushiBarBusinessLogic/WorkModeling.cs @@ -20,115 +20,129 @@ namespace SushiBarBusinessLogic private IOrderLogic? _orderLogic; - public WorkModeling(ILogger logger) + public WorkModeling(ILogger Logger) { - _logger = logger; + _logger = Logger; _rnd = new Random(1000); } - public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) + public void DoWork(IImplementerLogic ImplementerLogic, IOrderLogic OrderLogic) { - _orderLogic = orderLogic; - var implementers = implementerLogic.ReadList(null); - if (implementers == null) + _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) + + var Orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят }); + var BeingProcessedOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется}); + + if (Orders == null || BeingProcessedOrders == null || (Orders.Count == 0 && BeingProcessedOrders.Count == 0)) { _logger.LogWarning("DoWork. Orders is null or empty"); return; } - _logger.LogDebug("DoWork for {Count} orders", orders.Count); - foreach (var implementer in implementers) + + _logger.LogDebug("DoWork for {Count} orders", Orders.Count); + + foreach (var Implementer in Implementers) { - Task.Run(() => WorkerWorkAsync(implementer, orders)); + Task.Run(() => WorkerWorkAsync(Implementer, Orders)); } } - private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) + private async Task WorkerWorkAsync(ImplementerViewModel Implementer, List Orders) { - if (_orderLogic == null || implementer == null) + if (_orderLogic == null || Implementer == null) { return; } - await RunOrderInWork(implementer); + + await RunOrderInWork(Implementer); await Task.Run(() => { - foreach (var order in orders) + foreach (var Order in Orders) { try { - _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); - // пытаемся назначить заказ на исполнителя - _orderLogic.TakeOrderInWork(new OrderBindingModel + _logger.LogDebug("WorkerWorkAsync. Worker {Id} try get order {Order}", Implementer.Id, Order.Id); + bool AcquireResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { - Id = order.Id, - ImplementerId = implementer.Id + 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); + + if (!AcquireResult) + { + _logger.LogDebug("WorkerWorkAsync. Worker {Id} tried to get order {Order} but it's already acquired by other worker", Implementer.Id, Order.Id); + continue; + } + + Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 1000) * Order.Count); + + _logger.LogDebug("WorkerWorkAsync. Worker {Id} finish order {Order}", Implementer.Id, Order.Id); _orderLogic.FinishOrder(new OrderBindingModel { - Id = order.Id + 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)); + + Thread.Sleep(Implementer.Qualification * _rnd.Next(10, 100)); } }); } - private async Task RunOrderInWork(ImplementerViewModel implementer) + private async Task RunOrderInWork(ImplementerViewModel Implementer) { - if (_orderLogic == null || implementer == null) - { + if (_orderLogic == null || Implementer == null) return; - } + try { - var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel + var RunOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel { - ImplementerId = implementer.Id, + ImplementerId = Implementer.Id, Status = OrderStatus.Выполняется })); - if (runOrder == null) + + 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); + _logger.LogDebug("RunOrderInWork. Worker {Id} back to order {Order}", Implementer.Id, RunOrder.Id); + Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 300) * RunOrder.Count); + + _logger.LogDebug("RunOrderInWork. Worker {Id} finish order {Order}", Implementer.Id, RunOrder.Id); _orderLogic.FinishOrder(new OrderBindingModel { - Id = runOrder.Id + Id = RunOrder.Id }); - // отдыхаем - Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + + 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"); diff --git a/SushiBar/SushiBarView/FormMain.Designer.cs b/SushiBar/SushiBarView/FormMain.Designer.cs index e1140b5..3bcdd84 100644 --- a/SushiBar/SushiBarView/FormMain.Designer.cs +++ b/SushiBar/SushiBarView/FormMain.Designer.cs @@ -30,8 +30,6 @@ { dataGridView = new DataGridView(); ButtonCreateOrder = new Button(); - ButtonTakeOrderInWork = new Button(); - ButtonOrderReady = new Button(); ButtonIssuedOrder = new Button(); ButtonRef = new Button(); menuStrip = new MenuStrip(); @@ -69,29 +67,9 @@ ButtonCreateOrder.UseVisualStyleBackColor = true; ButtonCreateOrder.Click += ButtonCreateOrder_Click; // - // ButtonTakeOrderInWork - // - ButtonTakeOrderInWork.Location = new Point(1213, 80); - ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork"; - ButtonTakeOrderInWork.Size = new Size(147, 33); - ButtonTakeOrderInWork.TabIndex = 2; - ButtonTakeOrderInWork.Text = "Отдать на выполнение"; - ButtonTakeOrderInWork.UseVisualStyleBackColor = true; - ButtonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // ButtonOrderReady - // - ButtonOrderReady.Location = new Point(1213, 119); - ButtonOrderReady.Name = "ButtonOrderReady"; - ButtonOrderReady.Size = new Size(147, 33); - ButtonOrderReady.TabIndex = 3; - ButtonOrderReady.Text = "Заказ готов"; - ButtonOrderReady.UseVisualStyleBackColor = true; - ButtonOrderReady.Click += ButtonOrderReady_Click; - // // ButtonIssuedOrder // - ButtonIssuedOrder.Location = new Point(1213, 158); + ButtonIssuedOrder.Location = new Point(1213, 90); ButtonIssuedOrder.Name = "ButtonIssuedOrder"; ButtonIssuedOrder.Size = new Size(147, 33); ButtonIssuedOrder.TabIndex = 4; @@ -101,7 +79,7 @@ // // ButtonRef // - ButtonRef.Location = new Point(1213, 197); + ButtonRef.Location = new Point(1213, 142); ButtonRef.Name = "ButtonRef"; ButtonRef.Size = new Size(147, 33); ButtonRef.TabIndex = 5; @@ -128,28 +106,28 @@ // componentsToolStripMenuItem // componentsToolStripMenuItem.Name = "componentsToolStripMenuItem"; - componentsToolStripMenuItem.Size = new Size(180, 22); + componentsToolStripMenuItem.Size = new Size(149, 22); componentsToolStripMenuItem.Text = "Компоненты"; componentsToolStripMenuItem.Click += componentsToolStripMenuItem_Click; // // sushiToolStripMenuItem // sushiToolStripMenuItem.Name = "sushiToolStripMenuItem"; - sushiToolStripMenuItem.Size = new Size(180, 22); + sushiToolStripMenuItem.Size = new Size(149, 22); sushiToolStripMenuItem.Text = "Суши"; sushiToolStripMenuItem.Click += sushiToolStripMenuItem_Click; // // clientToolStripMenuItem // clientToolStripMenuItem.Name = "clientToolStripMenuItem"; - clientToolStripMenuItem.Size = new Size(180, 22); + clientToolStripMenuItem.Size = new Size(149, 22); clientToolStripMenuItem.Text = "Клиент"; clientToolStripMenuItem.Click += clientToolStripMenuItem_Click; // // employersToolStripMenuItem // employersToolStripMenuItem.Name = "employersToolStripMenuItem"; - employersToolStripMenuItem.Size = new Size(180, 22); + employersToolStripMenuItem.Size = new Size(149, 22); employersToolStripMenuItem.Text = "Исполнители"; employersToolStripMenuItem.Click += employersToolStripMenuItem_Click; // @@ -195,8 +173,6 @@ ClientSize = new Size(1381, 337); Controls.Add(ButtonRef); Controls.Add(ButtonIssuedOrder); - Controls.Add(ButtonOrderReady); - Controls.Add(ButtonTakeOrderInWork); Controls.Add(ButtonCreateOrder); Controls.Add(dataGridView); Controls.Add(menuStrip); @@ -215,8 +191,6 @@ private DataGridView dataGridView; private Button ButtonCreateOrder; - private Button ButtonTakeOrderInWork; - private Button ButtonOrderReady; private Button ButtonIssuedOrder; private Button ButtonRef; private MenuStrip menuStrip; diff --git a/SushiBar/SushiBarView/FormMain.cs b/SushiBar/SushiBarView/FormMain.cs index 56424cc..8fe11ae 100644 --- a/SushiBar/SushiBarView/FormMain.cs +++ b/SushiBar/SushiBarView/FormMain.cs @@ -79,58 +79,6 @@ namespace SushiBarView LoadData(); } } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new - OrderBindingModel - { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", - id); - try - { - var operationResult = _orderLogic.FinishOrder(new - OrderBindingModel - { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } private void ButtonIssuedOrder_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1)