ПИбд-21 Кувшинов Тимур сложная лаба 6 #23

Closed
TImourka wants to merge 4 commits from laba6complicated into laba5complicated
8 changed files with 298 additions and 12 deletions
Showing only changes of commit 2ae13a6dfe - Show all commits

View File

@ -17,6 +17,7 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
static readonly object locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
@ -81,6 +82,8 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
if (element.ImplementerId.HasValue)
model.ImplementerId = element.ImplementerId;
OrderStatus oldStatus = model.Status;
model.Status = status;
if (model.Status == OrderStatus.Выдан)
@ -96,7 +99,10 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
lock (locker)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
}
public bool FinishOrder(OrderBindingModel model)

View File

@ -0,0 +1,144 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace AutomobilePlantBusinessLogic.BusinessLogics
{
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
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
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
});
// отдыхаем
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

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

View File

@ -0,0 +1,106 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace AutomobilePlantRestApi.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<ImplementerController> 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<OrderViewModel>? 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;
}
}
}
}

View File

@ -12,9 +12,11 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<ICarStorage, CarStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ICarLogic, CarLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

View File

@ -33,6 +33,7 @@
toolStripMenuItemComponents = new ToolStripMenuItem();
toolStripMenuItemCars = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
implementersToolStripMenuItem = new ToolStripMenuItem();
reportsToolStripMenuItem = new ToolStripMenuItem();
carsListToolStripMenuItem = new ToolStripMenuItem();
componentsByCarsToolStripMenuItem = new ToolStripMenuItem();
@ -41,14 +42,14 @@
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRefresh = new Button();
implementersToolStripMenuItem = new ToolStripMenuItem();
startWorkingsToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItemCatalogs, reportsToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItemCatalogs, reportsToolStripMenuItem, startWorkingsToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(800, 24);
@ -65,24 +66,31 @@
// toolStripMenuItemComponents
//
toolStripMenuItemComponents.Name = "toolStripMenuItemComponents";
toolStripMenuItemComponents.Size = new Size(143, 22);
toolStripMenuItemComponents.Size = new Size(180, 22);
toolStripMenuItemComponents.Text = "Components";
toolStripMenuItemComponents.Click += ComponentsToolStripMenuItem_Click;
//
// toolStripMenuItemCars
//
toolStripMenuItemCars.Name = "toolStripMenuItemCars";
toolStripMenuItemCars.Size = new Size(143, 22);
toolStripMenuItemCars.Size = new Size(180, 22);
toolStripMenuItemCars.Text = "Cars";
toolStripMenuItemCars.Click += CarsToolStripMenuItem_Click;
//
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(143, 22);
clientsToolStripMenuItem.Size = new Size(180, 22);
clientsToolStripMenuItem.Text = "Clients";
clientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click;
//
// implementersToolStripMenuItem
//
implementersToolStripMenuItem.Name = "implementersToolStripMenuItem";
implementersToolStripMenuItem.Size = new Size(180, 22);
implementersToolStripMenuItem.Text = "Implementers";
implementersToolStripMenuItem.Click += implementersToolStripMenuItem_Click;
//
// reportsToolStripMenuItem
//
reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { carsListToolStripMenuItem, componentsByCarsToolStripMenuItem, ordersListToolStripMenuItem });
@ -150,12 +158,12 @@
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// implementersToolStripMenuItem
// startWorkingsToolStripMenuItem
//
implementersToolStripMenuItem.Name = "implementersToolStripMenuItem";
implementersToolStripMenuItem.Size = new Size(180, 22);
implementersToolStripMenuItem.Text = "Implementers";
implementersToolStripMenuItem.Click += implementersToolStripMenuItem_Click;
startWorkingsToolStripMenuItem.Name = "startWorkingsToolStripMenuItem";
startWorkingsToolStripMenuItem.Size = new Size(94, 20);
startWorkingsToolStripMenuItem.Text = "Start workings";
startWorkingsToolStripMenuItem.Click += startWorkingsToolStripMenuItem_Click;
//
// FormMain
//
@ -193,5 +201,6 @@
private ToolStripMenuItem ordersListToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem implementersToolStripMenuItem;
private ToolStripMenuItem startWorkingsToolStripMenuItem;
}
}

View File

@ -10,12 +10,14 @@ namespace AutomobilePlantView
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -109,6 +111,12 @@ namespace AutomobilePlantView
}
}
private void startWorkingsToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));

View File

@ -49,6 +49,7 @@ namespace AutomobilePlantView
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();