fix logic, formmain, full lab6

This commit is contained in:
DavidMakarov 2024-04-22 20:38:34 +04:00
parent 1726a3c9d7
commit b92c24b8d3
11 changed files with 428 additions and 391 deletions

View File

@ -103,6 +103,7 @@ namespace FlowerShopView
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
FlowerId = Convert.ToInt32(comboBoxFlower.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)

View File

@ -20,182 +20,190 @@
base.Dispose(disposing);
}
#region Windows Form Designer generated code
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
ЦветыToolStripMenuItem = new ToolStripMenuItem();
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem();
списокЦветковToolStripMenuItem = new ToolStripMenuItem();
компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonRef = new Button();
запускToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(964, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
//
// ЦветыToolStripMenuItem
//
ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem";
ЦветыToolStripMenuItem.Size = new Size(180, 22);
ЦветыToolStripMenuItem.Text = "Цветы";
ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click;
//
// КомпонентыToolStripMenuItem
//
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(180, 22);
КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(180, 22);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(180, 22);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(60, 20);
отчётыToolStripMenuItem.Text = "Отчёты";
//
// списокЦветковToolStripMenuItem
//
списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem";
списокЦветковToolStripMenuItem.Size = new Size(204, 22);
списокЦветковToolStripMenuItem.Text = "Список цветков";
списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click;
//
// компонентыПоЦветамToolStripMenuItem
//
компонентыПоЦветамToolStripMenuItem.Name = омпонентыПоЦветамToolStripMenuItem";
компонентыПоЦветамToolStripMenuItem.Size = new Size(204, 22);
компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам";
компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click;
//
// списокЗаказовToolStripMenuItem
//
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(204, 22);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 27);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(739, 411);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(775, 55);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(158, 32);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(775, 110);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(158, 32);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonRef
//
buttonRef.Location = new Point(775, 165);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(158, 32);
buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// запускToolStripMenuItem
//
запускToolStripMenuItem.Name = апускToolStripMenuItem";
запускToolStripMenuItem.Size = new Size(92, 20);
запускToolStripMenuItem.Text = "Запуск работ";
запускToolStripMenuItem.Click += запускToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(964, 450);
Controls.Add(buttonRef);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Цветочный магазин";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
ЦветыToolStripMenuItem = new ToolStripMenuItem();
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem();
списокЦветковToolStripMenuItem = new ToolStripMenuItem();
компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
запускToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(7, 3, 0, 3);
menuStrip1.Size = new Size(1102, 30);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
//
// ЦветыToolStripMenuItem
//
ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem";
ЦветыToolStripMenuItem.Size = new Size(185, 26);
ЦветыToolStripMenuItem.Text = "Цветы";
ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click;
//
// КомпонентыToolStripMenuItem
//
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(185, 26);
КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(185, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(185, 26);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(73, 24);
отчётыToolStripMenuItem.Text = "Отчёты";
//
// списокЦветковToolStripMenuItem
//
списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem";
списокЦветковToolStripMenuItem.Size = new Size(258, 26);
списокЦветковToolStripMenuItem.Text = "Список цветков";
списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click;
//
// компонентыПоЦветамToolStripMenuItem
//
компонентыПоЦветамToolStripMenuItem.Name = омпонентыПоЦветамToolStripMenuItem";
компонентыПоЦветамToolStripMenuItem.Size = new Size(258, 26);
компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам";
компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click;
//
// списокЗаказовToolStripMenuItem
//
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(258, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
//
// запускToolStripMenuItem
//
запускToolStripMenuItem.Name = апускToolStripMenuItem";
запускToolStripMenuItem.Size = new Size(114, 24);
запускToolStripMenuItem.Text = "Запуск работ";
запускToolStripMenuItem.Click += запускToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(14, 36);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(845, 548);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(886, 73);
buttonCreateOrder.Margin = new Padding(3, 4, 3, 4);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(181, 43);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(886, 147);
buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(181, 43);
buttonIssuedOrder.TabIndex = 3;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(886, 220);
buttonRef.Margin = new Padding(3, 4, 3, 4);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(181, 43);
buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1102, 600);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Margin = new Padding(3, 4, 3, 4);
Name = "FormMain";
Text = "Цветочный магазин";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
#endregion
private MenuStrip menuStrip1;
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ЦветыToolStripMenuItem;
private ToolStripMenuItem КомпонентыToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonIssuedOrder;
private Button buttonRef;
private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem списокЦветковToolStripMenuItem;

View File

@ -35,9 +35,6 @@ namespace FlowerShopView
dataGridView.Columns["FlowerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["FlowerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
@ -71,55 +68,6 @@ namespace FlowerShopView
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)

View File

@ -18,7 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>

View File

@ -1,5 +1,4 @@
using DocumentFormat.OpenXml.EMMA;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
@ -98,8 +97,8 @@ namespace FlowerShopBusinessLogic.BusinessLogics
model.DateCreate = element.DateCreate;
model.DateImplement = element.DateImplement;
model.ClientId = element.ClientId;
model.ImplementerId = element.ImplementerId;
model.Status = element.Status;
if (!model.ImplementerId.HasValue) model.ImplementerId = element.ImplementerId;
model.Status = element.Status;
model.Count = element.Count;
model.Sum = element.Sum;

View File

@ -9,112 +9,144 @@ namespace FlowerShopBusinessLogic.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));
}
}
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));
}
});
}
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;
}
}
}
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.Принят });
var BeingProcessedOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется });
// in case there are BeingProcessed orders but no Accepted orders
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)
{
Task.Run(() => WorkerWorkAsync(Implementer, Orders));
}
}
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("WorkerWorkAsync. Worker {Id} try get order {Order}", Implementer.Id, Order.Id);
// TakeOrderInWork will fail when the worker tries to change status to BeingProcessed when the order is already BeingProcessed
// which would happen when other worker already acquired that order
bool AcquireResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = Order.Id,
ImplementerId = Implementer.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
});
}
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("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
});
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

@ -3,6 +3,7 @@ using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace FlowerShopDatabaseImplement.Implements
{
@ -12,93 +13,96 @@ namespace FlowerShopDatabaseImplement.Implements
{
using var context = new FlowerShopDatabase();
return context.Orders
.Select(x => AccessFlowerStorage(x.GetViewModel))
.ToList();
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new FlowerShopDatabase();
if (model.DateFrom.HasValue)
{
return context.Orders
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
&& (!model.ClientId.HasValue || x.ClientId == model.ClientId))
.Select(x => AccessFlowerStorage(x.GetViewModel)).ToList();
&& (!model.ClientId.HasValue || x.ClientId == model.ClientId))
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => (model.Id.HasValue && x.Id == model.Id)
|| (model.ClientId.HasValue && x.ClientId == model.ClientId)
|| (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId)
|| (model.Status.HasValue && x.Status == model.Status))
.Select(x => AccessFlowerStorage(x.GetViewModel)).ToList();
|| (model.ClientId.HasValue && x.ClientId == model.ClientId)
|| (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId)
|| (model.Status.HasValue && x.Status == model.Status))
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.Status.HasValue)
return null;
}
using var context = new FlowerShopDatabase();
return AccessFlowerStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel);
return context.Orders
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)
|| (model.ImplementerId.HasValue && model.Status.HasValue && x.ImplementerId == model.ImplementerId && x.Status == model.Status))?
.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
if (model == null)
return null;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new FlowerShopDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return AccessFlowerStorage(newOrder.GetViewModel);
return context.Orders.Include(x => x.Flower).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new FlowerShopDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id ==
model.Id);
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return AccessFlowerStorage(order.GetViewModel);
return context.Orders.Include(x => x.Flower).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new FlowerShopDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return AccessFlowerStorage(element.GetViewModel);
}
return null;
}
var order = context.Orders.Include(x => x.Flower).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(rec => rec.Id == model.Id);
public static OrderViewModel AccessFlowerStorage(OrderViewModel model)
{
if (model == null)
if (order == null)
return null;
using var context = new FlowerShopDatabase();
foreach (var Flower in context.Flowers)
{
if (Flower.Id == model.FlowerId)
{
model.FlowerName = Flower.FlowerName;
break;
}
}
foreach (var client in context.Clients)
{
if (client.Id == model.ClientId)
{
model.ClientFIO = client.ClientFIO;
return model;
}
}
return model;
context.Orders.Remove(order);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FlowerShopDatabaseImplement.Migrations
{
[DbContext(typeof(FlowerShopDatabase))]
[Migration("20240418172148_InitCreate")]
[Migration("20240422161656_InitCreate")]
partial class InitCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -176,6 +176,8 @@ namespace FlowerShopDatabaseImplement.Migrations
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FlowerId");
b.HasIndex("ImplementerId");
@ -204,15 +206,27 @@ namespace FlowerShopDatabaseImplement.Migrations
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", null)
b.HasOne("FlowerShopDatabaseImplement.Models.Client", "Client")
.WithMany()
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower")
.WithMany("Orders")
.HasForeignKey("FlowerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", null)
b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Flower");
b.Navigation("Implementer");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Component", b =>

View File

@ -114,6 +114,12 @@ namespace FlowerShopDatabaseImplement.Migrations
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Flowers_FlowerId",
column: x => x.FlowerId,
@ -137,6 +143,11 @@ namespace FlowerShopDatabaseImplement.Migrations
table: "FlowerComponents",
column: "FlowerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_FlowerId",
table: "Orders",
@ -150,9 +161,6 @@ namespace FlowerShopDatabaseImplement.Migrations
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "FlowerComponents");
@ -162,6 +170,9 @@ namespace FlowerShopDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Flowers");

View File

@ -174,6 +174,8 @@ namespace FlowerShopDatabaseImplement.Migrations
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FlowerId");
b.HasIndex("ImplementerId");
@ -202,15 +204,27 @@ namespace FlowerShopDatabaseImplement.Migrations
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", null)
b.HasOne("FlowerShopDatabaseImplement.Models.Client", "Client")
.WithMany()
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower")
.WithMany("Orders")
.HasForeignKey("FlowerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", null)
b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Flower");
b.Navigation("Implementer");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Component", b =>

View File

@ -10,8 +10,11 @@ namespace FlowerShopDatabaseImplement.Models
{
public int Id { get; private set; }
public int FlowerId { get; private set; }
public virtual Flower Flower { get; set; }
public int ClientId { get; private set; }
public virtual Client Client { get; set; }
public int? ImplementerId { get; private set; }
public virtual Implementer? Implementer { get; set; }
[Required]
public int Count { get; set; }
[Required]
@ -56,6 +59,9 @@ namespace FlowerShopDatabaseImplement.Models
FlowerId = FlowerId,
ClientId = ClientId,
ImplementerId = ImplementerId,
FlowerName = Flower.FlowerName,
ClientFIO = Client.ClientFIO,
ImplementerFIO = Implementer?.ImplementerFIO,
Count = Count,
Sum = Sum,
Status = Status,