Классы имитации работы исполнителей и доработка OrderLogic

This commit is contained in:
prodigygirl 2023-04-09 18:55:27 +04:00
parent 1d72a67dab
commit 24305408dc
4 changed files with 181 additions and 17 deletions

View File

@ -55,11 +55,12 @@ namespace FurnitureAssemblyBusinessLogic
public bool TakeOrderInWork(OrderBindingModel model)
{
model = Find(model);
if (model == null)
var modelNew = ReadElement(new OrderSearchModel { Id = model.Id }); // в связи с обновлением контракта, предыдущий метод не нужен
if (modelNew == null)
{
return false;
}
model.Status = modelNew.Status;
if (!ChangeStatus(model, OrderStatus.Выполняется))
{
_logger.LogWarning("Order's status is wrong");
@ -71,32 +72,37 @@ namespace FurnitureAssemblyBusinessLogic
public bool FinishOrder(OrderBindingModel model)
{
model = Find(model);
if (model == null) {
var modelNew = ReadElement(new OrderSearchModel { Id = model.Id}); // в связи с обновлением контракта, предыдущий метод не нужен
if (modelNew == null) {
return false;
}
model.Status = modelNew.Status;
if (!ChangeStatus(model, OrderStatus.Готов))
{
_logger.LogWarning("Order's status is wrong");
return false;
}
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool DeliveryOrder(OrderBindingModel model)
{
model = Find(model);
if (model == null)
var modelNew = ReadElement(new OrderSearchModel { Id = model.Id }); // в связи с обновлением контракта, предыдущий метод не нужен
if (modelNew == null)
{
return false;
}
model.Status = modelNew.Status;
model.ImplementerId = modelNew.ImplementerId;
model.DateImplement = modelNew.DateImplement;
if (!ChangeStatus(model, OrderStatus.Выдан))
{
_logger.LogWarning("Order's status is wrong");
return false;
}
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
@ -143,20 +149,21 @@ namespace FurnitureAssemblyBusinessLogic
model.Id, model.Status, model.DateCreate, model.FurnitureId, model.Count, model.Sum);
}
private OrderBindingModel? Find(OrderBindingModel model)
public OrderViewModel? ReadElement(OrderSearchModel? model)
{
var modelView = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (modelView == null)
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Status: {Status}. ImplementerId: {ImplementerId} Id:{ Id}", model.Status, model.ImplementerId, model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
model.FurnitureId = modelView.FurnitureId;
model.DateCreate = modelView.DateCreate;
model.Count = modelView.Count;
model.Sum = modelView.Sum;
model.FurnitureId = model.FurnitureId;
model.Status = modelView.Status;
return model;
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
}
}

View File

@ -0,0 +1,146 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace FurnitureAssemblyBusinessLogic
{
public class WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> 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));
}
}
/// <summary>
/// Иммитация работы исполнителя
/// </summary>
/// <param name="implementer"></param>
/// <param name="orders"></param>
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> 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,
ImplementerId = implementer.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));
}
});
}
/// <summary>
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
/// </summary>
/// <param name="implementer"></param>
/// <returns></returns>
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,
ImplementerId = implementer.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;
}
}
}
}

View File

@ -11,6 +11,7 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
{
public interface IOrderLogic
{
OrderViewModel? ReadElement(OrderSearchModel? model);
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);

View File

@ -0,0 +1,10 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
{
public interface IWorkProcess
{
/// <summary>
/// Запуск работ
/// </summary>
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}