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 var operationResult = _logicO.CreateOrder(new OrderBindingModel
{ {
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
FlowerId = Convert.ToInt32(comboBoxFlower.SelectedValue), FlowerId = Convert.ToInt32(comboBoxFlower.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text), Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text) Sum = Convert.ToDouble(textBoxSum.Text)

View File

@ -38,21 +38,23 @@
списокЦветковToolStripMenuItem = new ToolStripMenuItem(); списокЦветковToolStripMenuItem = new ToolStripMenuItem();
компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem(); компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
запускToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
buttonCreateOrder = new Button(); buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button(); buttonIssuedOrder = new Button();
buttonRef = new Button(); buttonRef = new Button();
запускToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// menuStrip1 // menuStrip1
// //
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускToolStripMenuItem }); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускToolStripMenuItem });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(964, 24); menuStrip1.Padding = new Padding(7, 3, 0, 3);
menuStrip1.Size = new Size(1102, 30);
menuStrip1.TabIndex = 0; menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1"; menuStrip1.Text = "menuStrip1";
// //
@ -60,34 +62,34 @@
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники"; справочникиToolStripMenuItem.Text = "Справочники";
// //
// ЦветыToolStripMenuItem // ЦветыToolStripMenuItem
// //
ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem"; ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem";
ЦветыToolStripMenuItem.Size = new Size(180, 22); ЦветыToolStripMenuItem.Size = new Size(185, 26);
ЦветыToolStripMenuItem.Text = "Цветы"; ЦветыToolStripMenuItem.Text = "Цветы";
ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click; ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click;
// //
// КомпонентыToolStripMenuItem // КомпонентыToolStripMenuItem
// //
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(180, 22); КомпонентыToolStripMenuItem.Size = new Size(185, 26);
КомпонентыToolStripMenuItem.Text = "Компоненты"; КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
// //
// клиентыToolStripMenuItem // клиентыToolStripMenuItem
// //
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(180, 22); клиентыToolStripMenuItem.Size = new Size(185, 26);
клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
// //
// исполнителиToolStripMenuItem // исполнителиToolStripMenuItem
// //
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem"; исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(180, 22); исполнителиToolStripMenuItem.Size = new Size(185, 26);
исполнителиToolStripMenuItem.Text = "Исполнители"; исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
// //
@ -95,88 +97,94 @@
// //
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem }); отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(60, 20); отчётыToolStripMenuItem.Size = new Size(73, 24);
отчётыToolStripMenuItem.Text = "Отчёты"; отчётыToolStripMenuItem.Text = "Отчёты";
// //
// списокЦветковToolStripMenuItem // списокЦветковToolStripMenuItem
// //
списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem"; списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem";
списокЦветковToolStripMenuItem.Size = new Size(204, 22); списокЦветковToolStripMenuItem.Size = new Size(258, 26);
списокЦветковToolStripMenuItem.Text = "Список цветков"; списокЦветковToolStripMenuItem.Text = "Список цветков";
списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click; списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click;
// //
// компонентыПоЦветамToolStripMenuItem // компонентыПоЦветамToolStripMenuItem
// //
компонентыПоЦветамToolStripMenuItem.Name = омпонентыПоЦветамToolStripMenuItem"; компонентыПоЦветамToolStripMenuItem.Name = омпонентыПоЦветамToolStripMenuItem";
компонентыПоЦветамToolStripMenuItem.Size = new Size(204, 22); компонентыПоЦветамToolStripMenuItem.Size = new Size(258, 26);
компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам"; компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам";
компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click; компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click;
// //
// списокЗаказовToolStripMenuItem // списокЗаказовToolStripMenuItem
// //
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(204, 22); списокЗаказовToolStripMenuItem.Size = new Size(258, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
// //
// запускToolStripMenuItem
//
запускToolStripMenuItem.Name = апускToolStripMenuItem";
запускToolStripMenuItem.Size = new Size(114, 24);
запускToolStripMenuItem.Text = "Запуск работ";
запускToolStripMenuItem.Click += запускToolStripMenuItem_Click;
//
// dataGridView // dataGridView
// //
dataGridView.BackgroundColor = Color.White; dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 27); dataGridView.Location = new Point(14, 36);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView"; dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 25; dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(739, 411); dataGridView.Size = new Size(845, 548);
dataGridView.TabIndex = 1; dataGridView.TabIndex = 1;
// //
// buttonCreateOrder // buttonCreateOrder
// //
buttonCreateOrder.Location = new Point(775, 55); buttonCreateOrder.Location = new Point(886, 73);
buttonCreateOrder.Margin = new Padding(3, 4, 3, 4);
buttonCreateOrder.Name = "buttonCreateOrder"; buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(158, 32); buttonCreateOrder.Size = new Size(181, 43);
buttonCreateOrder.TabIndex = 2; buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ"; buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click; buttonCreateOrder.Click += ButtonCreateOrder_Click;
// //
// buttonTakeOrderInWork // buttonIssuedOrder
// //
buttonTakeOrderInWork.Location = new Point(775, 110); buttonIssuedOrder.Location = new Point(886, 147);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4);
buttonTakeOrderInWork.Size = new Size(158, 32); buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonTakeOrderInWork.TabIndex = 3; buttonIssuedOrder.Size = new Size(181, 43);
buttonTakeOrderInWork.Text = "Отдать на выполнение"; buttonIssuedOrder.TabIndex = 3;
buttonTakeOrderInWork.UseVisualStyleBackColor = true; buttonIssuedOrder.Text = "Заказ выдан";
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
// //
// buttonRef // buttonRef
// //
buttonRef.Location = new Point(775, 165); buttonRef.Location = new Point(886, 220);
buttonRef.Margin = new Padding(3, 4, 3, 4);
buttonRef.Name = "buttonRef"; buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(158, 32); buttonRef.Size = new Size(181, 43);
buttonRef.TabIndex = 6; buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список"; buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true; buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click; buttonRef.Click += ButtonRef_Click;
// //
// запускToolStripMenuItem
//
запускToolStripMenuItem.Name = апускToolStripMenuItem";
запускToolStripMenuItem.Size = new Size(92, 20);
запускToolStripMenuItem.Text = "Запуск работ";
запускToolStripMenuItem.Click += запускToolStripMenuItem_Click;
//
// FormMain // FormMain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(964, 450); ClientSize = new Size(1102, 600);
Controls.Add(buttonRef); Controls.Add(buttonRef);
Controls.Add(buttonTakeOrderInWork); Controls.Add(buttonIssuedOrder);
Controls.Add(buttonCreateOrder); Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView); Controls.Add(dataGridView);
Controls.Add(menuStrip1); Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1; MainMenuStrip = menuStrip1;
Margin = new Padding(3, 4, 3, 4);
Name = "FormMain"; Name = "FormMain";
Text = "Цветочный магазин"; Text = "Цветочный магазин";
Load += FormMain_Load; Load += FormMain_Load;
@ -195,7 +203,7 @@
private ToolStripMenuItem КомпонентыToolStripMenuItem; private ToolStripMenuItem КомпонентыToolStripMenuItem;
private DataGridView dataGridView; private DataGridView dataGridView;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private Button buttonTakeOrderInWork; private Button buttonIssuedOrder;
private Button buttonRef; private Button buttonRef;
private ToolStripMenuItem отчётыToolStripMenuItem; private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem списокЦветковToolStripMenuItem; private ToolStripMenuItem списокЦветковToolStripMenuItem;

View File

@ -35,9 +35,6 @@ namespace FlowerShopView
dataGridView.Columns["FlowerId"].Visible = false; dataGridView.Columns["FlowerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].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) catch (Exception ex)
@ -71,55 +68,6 @@ namespace FlowerShopView
LoadData(); 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) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)

View File

@ -18,7 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, 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="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"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>

View File

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

View File

@ -10,106 +10,138 @@ namespace FlowerShopBusinessLogic.BusinessLogics
public class WorkModeling : IWorkProcess public class WorkModeling : IWorkProcess
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Random _rnd; private readonly Random _rnd;
private IOrderLogic? _orderLogic; private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
public WorkModeling(ILogger<WorkModeling> Logger)
{ {
_logger = logger; _logger = Logger;
_rnd = new Random(1000); _rnd = new Random(1000);
} }
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic)
public void DoWork(IImplementerLogic ImplementerLogic, IOrderLogic OrderLogic)
{ {
_orderLogic = orderLogic; _orderLogic = OrderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null) var Implementers = ImplementerLogic.ReadList(null);
if (Implementers == null)
{ {
_logger.LogWarning("DoWork. Implementers is null"); _logger.LogWarning("DoWork. Implementers is null");
return; return;
} }
var orders = _orderLogic.ReadList(new OrderSearchModel
{ var Orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
Status = OrderStatus.Принят var BeingProcessedOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется });
}); // in case there are BeingProcessed orders but no Accepted orders
if (orders == null || orders.Count == 0)
if (Orders == null || BeingProcessedOrders == null || (Orders.Count == 0 && BeingProcessedOrders.Count == 0))
{ {
_logger.LogWarning("DoWork. Orders is null or empty"); _logger.LogWarning("DoWork. Orders is null or empty");
return; 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<OrderViewModel> orders)
private async Task WorkerWorkAsync(ImplementerViewModel Implementer, List<OrderViewModel> Orders)
{ {
if (_orderLogic == null || implementer == null) if (_orderLogic == null || Implementer == null)
{ {
return; return;
} }
await RunOrderInWork(implementer);
await RunOrderInWork(Implementer);
await Task.Run(() => await Task.Run(() =>
{ {
foreach (var order in orders) foreach (var Order in Orders)
{ {
try try
{ {
_logger.LogDebug("DoWork. Worker {Id} try get order { Order}", implementer.Id, order.Id); _logger.LogDebug("WorkerWorkAsync. Worker {Id} try get order {Order}", Implementer.Id, Order.Id);
_orderLogic.TakeOrderInWork(new OrderBindingModel
// 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, Id = Order.Id,
ImplementerId = implementer.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 _orderLogic.FinishOrder(new OrderBindingModel
{ {
Id = order.Id Id = Order.Id
}); });
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogWarning(ex, "Error try get work"); _logger.LogWarning(ex, "Error try get work");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error while do work"); _logger.LogError(ex, "Error while do work");
throw; 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; return;
}
try 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.Выполняется Status = OrderStatus.Выполняется
})); }));
if (runOrder == null)
if (RunOrder == null)
{ {
return; 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("RunOrderInWork. Worker {Id} back to order {Order}", Implementer.Id, RunOrder.Id);
_logger.LogDebug("DoWork. Worker {Id} finish 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 _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) catch (InvalidOperationException ex)
{ {
_logger.LogWarning(ex, "Error try get work"); _logger.LogWarning(ex, "Error try get work");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error while do work"); _logger.LogError(ex, "Error while do work");

View File

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

View File

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

View File

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

View File

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

View File

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