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

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

@ -9,112 +9,144 @@ namespace FlowerShopBusinessLogic.BusinessLogics
{ {
public class WorkModeling : IWorkProcess public class WorkModeling : IWorkProcess
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic; private readonly Random _rnd;
public WorkModeling(ILogger<WorkModeling> logger)
{ private IOrderLogic? _orderLogic;
_logger = logger;
_rnd = new Random(1000); public WorkModeling(ILogger<WorkModeling> Logger)
} {
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) _logger = Logger;
{ _rnd = new Random(1000);
_orderLogic = orderLogic; }
var implementers = implementerLogic.ReadList(null);
if (implementers == null) public void DoWork(IImplementerLogic ImplementerLogic, IOrderLogic OrderLogic)
{ {
_logger.LogWarning("DoWork. Implementers is null"); _orderLogic = OrderLogic;
return;
} var Implementers = ImplementerLogic.ReadList(null);
var orders = _orderLogic.ReadList(new OrderSearchModel
{ if (Implementers == null)
Status = OrderStatus.Принят {
}); _logger.LogWarning("DoWork. Implementers is null");
if (orders == null || orders.Count == 0) return;
{ }
_logger.LogWarning("DoWork. Orders is null or empty");
return; var Orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
} var BeingProcessedOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется });
_logger.LogDebug("DoWork for {Count} orders", orders.Count); // in case there are BeingProcessed orders but no Accepted orders
foreach (var implementer in implementers)
{ if (Orders == null || BeingProcessedOrders == null || (Orders.Count == 0 && BeingProcessedOrders.Count == 0))
Task.Run(() => WorkerWorkAsync(implementer, orders)); {
} _logger.LogWarning("DoWork. Orders is null or empty");
} return;
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders) }
{
if (_orderLogic == null || implementer == null) _logger.LogDebug("DoWork for {Count} orders", Orders.Count);
{
return; foreach (var Implementer in Implementers)
} {
await RunOrderInWork(implementer); Task.Run(() => WorkerWorkAsync(Implementer, Orders));
await Task.Run(() => }
{ }
foreach (var order in orders)
{ private async Task WorkerWorkAsync(ImplementerViewModel Implementer, List<OrderViewModel> Orders)
try {
{ if (_orderLogic == null || Implementer == null)
_logger.LogDebug("DoWork. Worker {Id} try get order { Order}", implementer.Id, order.Id); {
_orderLogic.TakeOrderInWork(new OrderBindingModel return;
{ }
Id = order.Id,
ImplementerId = implementer.Id await RunOrderInWork(Implementer);
});
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); await Task.Run(() =>
_logger.LogDebug("DoWork. Worker {Id} finish order{ Order}", implementer.Id, order.Id); {
_orderLogic.FinishOrder(new OrderBindingModel foreach (var Order in Orders)
{ {
Id = order.Id try
}); {
} _logger.LogDebug("WorkerWorkAsync. Worker {Id} try get order {Order}", Implementer.Id, Order.Id);
catch (InvalidOperationException ex)
{ // TakeOrderInWork will fail when the worker tries to change status to BeingProcessed when the order is already BeingProcessed
_logger.LogWarning(ex, "Error try get work"); // which would happen when other worker already acquired that order
} bool AcquireResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
catch (Exception ex) {
{ Id = Order.Id,
_logger.LogError(ex, "Error while do work"); ImplementerId = Implementer.Id
throw; });
}
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); 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;
private async Task RunOrderInWork(ImplementerViewModel implementer) }
{
if (_orderLogic == null || implementer == null) Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 1000) * Order.Count);
{
return; _logger.LogDebug("WorkerWorkAsync. Worker {Id} finish order {Order}", Implementer.Id, Order.Id);
} _orderLogic.FinishOrder(new OrderBindingModel
try {
{ Id = Order.Id
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel });
{ }
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется catch (InvalidOperationException ex)
})); {
if (runOrder == null) _logger.LogWarning(ex, "Error try get work");
{ }
return;
} catch (Exception ex)
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id); {
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count); _logger.LogError(ex, "Error while do work");
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); throw;
_orderLogic.FinishOrder(new OrderBindingModel }
{
Id = runOrder.Id Thread.Sleep(Implementer.Qualification * _rnd.Next(10, 100));
}); }
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); });
} }
catch (InvalidOperationException ex)
{ private async Task RunOrderInWork(ImplementerViewModel Implementer)
_logger.LogWarning(ex, "Error try get work"); {
} if (_orderLogic == null || Implementer == null)
catch (Exception ex) return;
{
_logger.LogError(ex, "Error while do work"); try
throw; {
} 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.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)
.ToList(); .Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.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,