From 6457bc4afaced49f5c9da6dc36712c2216d58981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D1=8F=D1=80=20=D0=90=D0=B3=D0=BB?= =?UTF-8?q?=D0=B8=D1=83=D0=BB=D0=BB=D0=BE=D0=B2?= Date: Mon, 6 Mar 2023 16:59:14 +0400 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B8=D0=BC=D0=B8=D1=82=D0=B0=D1=86=D0=B8=D1=8F?= =?UTF-8?q?=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D1=8B=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D0=BD=D0=B8=D1=82=D0=B5=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ConfectionaryBusinessLogic/OrderLogic.cs | 19 ++- ConfectionaryBusinessLogic/WorkModeling.cs | 148 ++++++++++++++++++ Confectionery/FormMain.cs | 10 +- Confectionery/Program.cs | 1 + .../BusinessLogicsContracts/IOrderLogic.cs | 3 +- .../BusinessLogicsContracts/IWorkProcess.cs | 10 ++ .../Controllers/ImplementerController.cs | 107 +++++++++++++ 7 files changed, 294 insertions(+), 4 deletions(-) create mode 100644 ConfectionaryBusinessLogic/WorkModeling.cs create mode 100644 ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs create mode 100644 ConfectioneryRestApi/Controllers/ImplementerController.cs diff --git a/ConfectionaryBusinessLogic/OrderLogic.cs b/ConfectionaryBusinessLogic/OrderLogic.cs index 1471185..f079f58 100644 --- a/ConfectionaryBusinessLogic/OrderLogic.cs +++ b/ConfectionaryBusinessLogic/OrderLogic.cs @@ -110,5 +110,22 @@ namespace ConfectioneryBusinessLogic.BusinessLogics } return true; } - } + + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. Id:{ Id}", 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; + } + } } diff --git a/ConfectionaryBusinessLogic/WorkModeling.cs b/ConfectionaryBusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..f19fafe --- /dev/null +++ b/ConfectionaryBusinessLogic/WorkModeling.cs @@ -0,0 +1,148 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryBusinessLogic +{ + 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/Confectionery/FormMain.cs b/Confectionery/FormMain.cs index 01ab4e4..4eb1dd5 100644 --- a/Confectionery/FormMain.cs +++ b/Confectionery/FormMain.cs @@ -12,13 +12,15 @@ namespace ConfectioneryView private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + 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) { @@ -207,7 +209,11 @@ namespace ConfectioneryView private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) { - + _workProcess.DoWork(( + Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, + _orderLogic); + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); } } } \ No newline at end of file diff --git a/Confectionery/Program.cs b/Confectionery/Program.cs index dc32af3..f081352 100644 --- a/Confectionery/Program.cs +++ b/Confectionery/Program.cs @@ -49,6 +49,7 @@ namespace ConfectioneryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs b/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs index 221258a..dfd1797 100644 --- a/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -7,7 +7,8 @@ namespace ConfectioneryContracts.BusinessLogicsContracts public interface IOrderLogic { List? ReadList(OrderSearchModel? model); - bool CreateOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel model); + bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); bool DeliveryOrder(OrderBindingModel model); diff --git a/ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs b/ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..5a1de4c --- /dev/null +++ b/ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,10 @@ +namespace ConfectioneryContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + /// + /// Запуск работ + /// + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/ConfectioneryRestApi/Controllers/ImplementerController.cs b/ConfectioneryRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..9664734 --- /dev/null +++ b/ConfectioneryRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,107 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels.Enums; +using Microsoft.AspNetCore.Mvc; + +namespace ConfectioneryRestApi.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; + } + } + } +}