From b92c24b8d3faa92143d5fbdd1c5744f1f0b0db99 Mon Sep 17 00:00:00 2001 From: DavidMakarov Date: Mon, 22 Apr 2024 20:38:34 +0400 Subject: [PATCH] fix logic, formmain, full lab6 --- FlowerShop/FlowerShop/FormCreateOrder.cs | 1 + FlowerShop/FlowerShop/FormMain.Designer.cs | 344 +++++++++--------- FlowerShop/FlowerShop/FormMain.cs | 52 --- FlowerShop/FlowerShop/FormMain.resx | 2 +- .../BusinessLogics/OrderLogic.cs | 7 +- .../BusinessLogics/WorkModeling.cs | 248 +++++++------ .../Implements/OrderStorage.cs | 104 +++--- ... => 20240422161656_InitCreate.Designer.cs} | 20 +- ...Create.cs => 20240422161656_InitCreate.cs} | 17 +- .../FlowerShopDatabaseModelSnapshot.cs | 18 +- .../Models/Order.cs | 6 + 11 files changed, 428 insertions(+), 391 deletions(-) rename FlowerShop/FlowerShopDatabaseImplement/Migrations/{20240418172148_InitCreate.Designer.cs => 20240422161656_InitCreate.Designer.cs} (93%) rename FlowerShop/FlowerShopDatabaseImplement/Migrations/{20240418172148_InitCreate.cs => 20240422161656_InitCreate.cs} (94%) diff --git a/FlowerShop/FlowerShop/FormCreateOrder.cs b/FlowerShop/FlowerShop/FormCreateOrder.cs index 842786f..8ac37a0 100644 --- a/FlowerShop/FlowerShop/FormCreateOrder.cs +++ b/FlowerShop/FlowerShop/FormCreateOrder.cs @@ -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) diff --git a/FlowerShop/FlowerShop/FormMain.Designer.cs b/FlowerShop/FlowerShop/FormMain.Designer.cs index 76e33b8..b8d27df 100644 --- a/FlowerShop/FlowerShop/FormMain.Designer.cs +++ b/FlowerShop/FlowerShop/FormMain.Designer.cs @@ -20,182 +20,190 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - 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(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; diff --git a/FlowerShop/FlowerShop/FormMain.cs b/FlowerShop/FlowerShop/FormMain.cs index dd21605..e19e7bc 100644 --- a/FlowerShop/FlowerShop/FormMain.cs +++ b/FlowerShop/FlowerShop/FormMain.cs @@ -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) diff --git a/FlowerShop/FlowerShop/FormMain.resx b/FlowerShop/FlowerShop/FormMain.resx index 5203d24..a0623c8 100644 --- a/FlowerShop/FlowerShop/FormMain.resx +++ b/FlowerShop/FlowerShop/FormMain.resx @@ -18,7 +18,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, ... System.Resources.ResXResourceWriter, System.Windows.Forms, ... this is my long stringthis is a comment - Blue + Blue [base64 mime encoded serialized .NET Framework object] diff --git a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs index 8b61226..0e7caba 100644 --- a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -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; diff --git a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/WorkModeling.cs b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/WorkModeling.cs index f720fa1..051d3f5 100644 --- a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/WorkModeling.cs +++ b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/WorkModeling.cs @@ -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 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 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 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 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; + } + } + } } \ No newline at end of file diff --git a/FlowerShop/FlowerShopDatabaseImplement/Implements/OrderStorage.cs b/FlowerShop/FlowerShopDatabaseImplement/Implements/OrderStorage.cs index 6e454c2..30ff169 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Implements/OrderStorage.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Implements/OrderStorage.cs @@ -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 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; } } } diff --git a/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240418172148_InitCreate.Designer.cs b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240422161656_InitCreate.Designer.cs similarity index 93% rename from FlowerShop/FlowerShopDatabaseImplement/Migrations/20240418172148_InitCreate.Designer.cs rename to FlowerShop/FlowerShopDatabaseImplement/Migrations/20240422161656_InitCreate.Designer.cs index 0384535..d6c1a9c 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240418172148_InitCreate.Designer.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240422161656_InitCreate.Designer.cs @@ -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 => diff --git a/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240418172148_InitCreate.cs b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240422161656_InitCreate.cs similarity index 94% rename from FlowerShop/FlowerShopDatabaseImplement/Migrations/20240418172148_InitCreate.cs rename to FlowerShop/FlowerShopDatabaseImplement/Migrations/20240422161656_InitCreate.cs index 6bcd782..e3cb0dc 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240418172148_InitCreate.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240422161656_InitCreate.cs @@ -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"); diff --git a/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs b/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs index 0ccf3ca..dc3a919 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs @@ -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 => diff --git a/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs b/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs index 87ff7a2..98ce151 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs @@ -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,