From 91fdd361b6216cf07134ee56fd24f49096e09be6 Mon Sep 17 00:00:00 2001 From: Inohara Date: Tue, 25 Apr 2023 08:54:06 +0400 Subject: [PATCH] =?UTF-8?q?=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/OrderLogic.cs | 17 ++- .../BusinessLogics/ShopLogic.cs | 144 ++++++++++++++---- .../BusinessLogics/WorkModeling.cs | 33 +++- .../IceCreamShop/FormMain.Designer.cs | 69 +++------ IceCreamShop/IceCreamShop/FormMain.cs | 53 ------- .../BusinessLogicsContracts/IShopLogic.cs | 2 + .../Enums/OrderStatus.cs | 3 +- .../Implements/OrderStorage.cs | 2 +- .../IceCreamShopDatabaseModelSnapshot.cs | 31 ++-- .../Models/Order.cs | 2 +- .../Models/Shop.cs | 41 +++-- 11 files changed, 212 insertions(+), 185 deletions(-) diff --git a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs index 09a0704..290bd73 100644 --- a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs @@ -110,13 +110,27 @@ namespace IceCreamBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(model)); } - if ((int)vmodel.Status + 1 != (int)orderStatus) + if ((int)vmodel.Status + 1 != (int)orderStatus && !(vmodel.Status == OrderStatus.Ожидается && orderStatus == OrderStatus.Готов)) { throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " + $"Текущий статус: {vmodel.Status} \n" + $"Планируемый статус: {orderStatus} \n" + $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}"); } + if (orderStatus == OrderStatus.Готов || orderStatus == OrderStatus.Ожидается) + { + var icecream = _iceCreamStorage.GetElement(new() { Id = vmodel.IceCreamId }); + + if (icecream == null || !_shopLogic.AddIceCream(icecream, vmodel.Count)) + { + _logger.LogWarning($"Не удалось заполнить магазины изделием '{icecream?.IceCreamName ?? string.Empty}' из заказа {vmodel.Id}"); + orderStatus = OrderStatus.Ожидается; + } + else + { + orderStatus = OrderStatus.Готов; + } + } model.Status = orderStatus; model.DateCreate = vmodel.DateCreate; if (model.DateImplement == null) @@ -134,7 +148,6 @@ namespace IceCreamBusinessLogic.BusinessLogics return true; } - public OrderViewModel? ReadElement(OrderSearchModel model) { if (model == null) diff --git a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/ShopLogic.cs b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/ShopLogic.cs index acbc42c..bc15aa5 100644 --- a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/ShopLogic.cs +++ b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/ShopLogic.cs @@ -76,49 +76,133 @@ namespace IceCreamBusinessLogic.BusinessLogics throw new ArgumentNullException("Count of iceCreams in supply myst be more than 0", nameof(count)); } - var shopElement = _shopStorage.GetElement(model); - if (shopElement == null) + _logger.LogInformation("AddPastryInShop. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) { - _logger.LogWarning("Required shop element not found in storage"); + _logger.LogWarning("AddPastryInShop element not found"); return false; } - _logger.LogInformation("Shop element found. ID: {0}, Name: {1}", shopElement.Id, shopElement.Name); + _logger.LogInformation("AddPastryInShop find. Id:{Id}", element.Id); - var countDocs = 0; - foreach (var doc in shopElement.ShopIceCreams) + if (element.ShopIceCreams.TryGetValue(iceCream.Id, out var sameIcecream)) { - countDocs += doc.Value.Item2; - } - if (shopElement.IceCreamMaxCount - countDocs >= count) - { - if (shopElement.ShopIceCreams.TryGetValue(iceCream.Id, out var sameDocument)) - { - shopElement.ShopIceCreams[iceCream.Id] = (iceCream, sameDocument.Item2 + count); - _logger.LogInformation("Same iceCream found by supply. Added {0} of {1} in {2} shop", count, iceCream.IceCreamName, shopElement.Name); - } - else - { - shopElement.ShopIceCreams[iceCream.Id] = (iceCream, count); - _logger.LogInformation("New iceCream added by supply. Added {0} of {1} in {2} shop", count, iceCream.IceCreamName, shopElement.Name); - } - _shopStorage.Update(new() - { - Id = shopElement.Id, - Name = shopElement.Name, - Adress = shopElement.Adress, - OpeningDate = shopElement.OpeningDate, - ShopIceCreams = shopElement.ShopIceCreams, - IceCreamMaxCount = shopElement.IceCreamMaxCount - }); + element.ShopIceCreams[iceCream.Id] = (iceCream, sameIcecream.Item2 + count); + _logger.LogInformation("Same iceCream found by supply. Added {0} of {1} in {2} shop", count, iceCream.IceCreamName, element.Name); } else { - _logger.LogWarning("Required shop is overflowed"); + element.ShopIceCreams[iceCream.Id] = (iceCream, count); + _logger.LogInformation("New iceCream added by supply. Added {0} of {1} in {2} shop", count, iceCream.IceCreamName, element.Name); + } + +/* var prevCount = element.ShopIceCreams.GetValueOrDefault(iceCream.Id, (iceCream, 0)).Item2; + element.ShopIceCreams[iceCream.Id] = (iceCream, prevCount + count); + _logger.LogInformation( + "AddPastryInShop. Has been added {count} {pastry} in {ShopName}", + count, iceCream.IceCreamName, element.Name); +*/ + _shopStorage.Update(new() + { + Id = element.Id, + Adress = element.Adress, + Name = element.Name, + OpeningDate = element.OpeningDate, + ShopIceCreams = element.ShopIceCreams + }); + return true; + + + /* var shopElement = _shopStorage.GetElement(model); + if (shopElement == null) + { + _logger.LogWarning("Required shop element not found in storage"); + return false; + } + _logger.LogInformation("Shop element found. ID: {0}, Name: {1}", shopElement.Id, shopElement.Name); + + var countIcecreams = 0; + foreach (var icecream in shopElement.ShopIceCreams) + { + countIcecreams += icecream.Value.Item2; + } + if (shopElement.IceCreamMaxCount - countIcecreams >= count) + { + if (shopElement.ShopIceCreams.TryGetValue(iceCream.Id, out var sameIcecream)) + { + shopElement.ShopIceCreams[iceCream.Id] = (iceCream, sameIcecream.Item2 + count); + _logger.LogInformation("Same iceCream found by supply. Added {0} of {1} in {2} shop", count, iceCream.IceCreamName, shopElement.Name); + } + else + { + shopElement.ShopIceCreams[iceCream.Id] = (iceCream, count); + _logger.LogInformation("New iceCream added by supply. Added {0} of {1} in {2} shop", count, iceCream.IceCreamName, shopElement.Name); + } + _shopStorage.Update(new() + { + Id = shopElement.Id, + Name = shopElement.Name, + Adress = shopElement.Adress, + OpeningDate = shopElement.OpeningDate, + ShopIceCreams = shopElement.ShopIceCreams, + IceCreamMaxCount = shopElement.IceCreamMaxCount + }); + } + else + { + _logger.LogWarning("Required shop is overflowed"); + return false; + } + return true;*/ + } + + public bool AddIceCream(IIceCreamModel icecream, int count) + { + if (count <= 0) + { + _logger.LogWarning("AddPastriesInShops. Количество добавляемых изделий должно быть больше 0. Количество - {count}", count); return false; } + var freePlaces = GetFreePlaces(count); + if (freePlaces < 0) + { + _logger.LogInformation("AddPastriesInShops. Не удалось добавить изделия в магазины, поскольку они переполнены." + + "Освободите магазины на {places} изделий", -freePlaces); + return false; + } + foreach (var shop in _shopStorage.GetFullList()) + { +/* int freeInShop = shop.IceCreamMaxCount - shop.ShopIceCreams.Select(x => x.Value.Item2).Sum(); + if (freeInShop < count) continue;*/ + + var cnt = Math.Min(count, shop.IceCreamMaxCount - shop.ShopIceCreams.Select(x => x.Value.Item2).Sum()); + if (cnt <= 0) + { + continue; + } + if (!SupplyIceCreams(new() { Id = shop.Id }, icecream, cnt)) + { + _logger.LogWarning("При добавления изделий во все магазины произошла ошибка"); + return false; + } + count -= cnt; + if (count == 0) + { + return true; + } + } return true; } + //свободные места со всех магазинов + public int GetFreePlaces(int countIceCreams) + { + // Сумма разностей между максимальный кол-вом изделий и суммой всех изделий в магазине + return _shopStorage.GetFullList() + .Select(x => x.IceCreamMaxCount - x.ShopIceCreams.Select(p => p.Value.Item2).Sum()) + .Sum() - countIceCreams; + } + public bool SellIceCreams(IIceCreamModel iceCream, int count) { return _shopStorage.SellIceCreams(iceCream, count); diff --git a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/WorkModeling.cs b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/WorkModeling.cs index c4f04ef..65fe55a 100644 --- a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/WorkModeling.cs +++ b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/WorkModeling.cs @@ -32,7 +32,7 @@ namespace IceCreamBusinessLogic.BusinessLogic } // Поскольку у нас могут быть заказы в работе мы не дожны заканчивать работы, если нет Принятых заказов // Поэтому находим заказы в работе и продолжаем работу, если они есть - var orders = _orderLogic.ReadList(new OrderSearchModel { Statusses = new() { OrderStatus.Принят, OrderStatus.Выполняется } }); + var orders = _orderLogic.ReadList(new OrderSearchModel { Statusses = new() { OrderStatus.Принят, OrderStatus.Выполняется, OrderStatus.Ожидается } }); if (orders == null || orders.Count == 0) { _logger.LogWarning("DoWork. Orders is null or empty"); @@ -56,7 +56,36 @@ namespace IceCreamBusinessLogic.BusinessLogic { return; } - await RunOrderInWork(implementer, orders); + + // Для заказов находящихся в статусе ожидания работник не должен делать никакую работу, а должен просто пытаться перевести их в статус готов + await Task.Run(() => + { + foreach (var order in orders.Where(x => x.Status == OrderStatus.Ожидается && x.ImplementerId == implementer.Id)) + { + try + { + _orderLogic.DeliveryOrder(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)); + } + }); + + await RunOrderInWork(implementer, orders); await Task.Run(() => { diff --git a/IceCreamShop/IceCreamShop/FormMain.Designer.cs b/IceCreamShop/IceCreamShop/FormMain.Designer.cs index d957b04..f5a299b 100644 --- a/IceCreamShop/IceCreamShop/FormMain.Designer.cs +++ b/IceCreamShop/IceCreamShop/FormMain.Designer.cs @@ -34,7 +34,6 @@ this.dataGridView = new System.Windows.Forms.DataGridView(); this.menuStrip = new System.Windows.Forms.MenuStrip(); this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.мороженоеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -44,10 +43,10 @@ this.iceCreamComponentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.iceCreamToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ordersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.DoWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.listShopsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.shopWorkloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ordersByDateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.DoWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.buttonSupplyShop = new System.Windows.Forms.Button(); this.SellIceCreamButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); @@ -56,8 +55,7 @@ // // buttonUpdate // - this.buttonUpdate.Location = new System.Drawing.Point(1235, 149); - this.buttonUpdate.Location = new System.Drawing.Point(1053, 390); + this.buttonUpdate.Location = new System.Drawing.Point(1231, 392); this.buttonUpdate.Name = "buttonUpdate"; this.buttonUpdate.Size = new System.Drawing.Size(194, 49); this.buttonUpdate.TabIndex = 13; @@ -67,8 +65,7 @@ // // buttonSetToFinish // - this.buttonSetToFinish.Location = new System.Drawing.Point(1235, 94); - this.buttonSetToFinish.Location = new System.Drawing.Point(1053, 193); + this.buttonSetToFinish.Location = new System.Drawing.Point(1231, 90); this.buttonSetToFinish.Name = "buttonSetToFinish"; this.buttonSetToFinish.Size = new System.Drawing.Size(194, 49); this.buttonSetToFinish.TabIndex = 12; @@ -76,30 +73,9 @@ this.buttonSetToFinish.UseVisualStyleBackColor = true; this.buttonSetToFinish.Click += new System.EventHandler(this.buttonSetToFinish_Click); // - // buttonSetToDone - // - this.buttonSetToDone.Location = new System.Drawing.Point(1053, 139); - this.buttonSetToDone.Name = "buttonSetToDone"; - this.buttonSetToDone.Size = new System.Drawing.Size(194, 49); - this.buttonSetToDone.TabIndex = 11; - this.buttonSetToDone.Text = "Заказ готов"; - this.buttonSetToDone.UseVisualStyleBackColor = true; - this.buttonSetToDone.Click += new System.EventHandler(this.buttonSetToDone_Click); - // - // buttonSetToWork - // - this.buttonSetToWork.Location = new System.Drawing.Point(1053, 87); - this.buttonSetToWork.Name = "buttonSetToWork"; - this.buttonSetToWork.Size = new System.Drawing.Size(194, 49); - this.buttonSetToWork.TabIndex = 10; - this.buttonSetToWork.Text = "Отдать на выполнение"; - this.buttonSetToWork.UseVisualStyleBackColor = true; - this.buttonSetToWork.Click += new System.EventHandler(this.buttonSetToWork_Click); - // // buttonCreateOrder // - this.buttonCreateOrder.Location = new System.Drawing.Point(1235, 39); - this.buttonCreateOrder.Location = new System.Drawing.Point(1053, 33); + this.buttonCreateOrder.Location = new System.Drawing.Point(1231, 35); this.buttonCreateOrder.Name = "buttonCreateOrder"; this.buttonCreateOrder.Size = new System.Drawing.Size(194, 49); this.buttonCreateOrder.TabIndex = 9; @@ -114,8 +90,7 @@ this.dataGridView.Name = "dataGridView"; this.dataGridView.RowHeadersWidth = 51; this.dataGridView.RowTemplate.Height = 29; - this.dataGridView.Size = new System.Drawing.Size(1215, 407); - this.dataGridView.Size = new System.Drawing.Size(1033, 407); + this.dataGridView.Size = new System.Drawing.Size(1202, 407); this.dataGridView.TabIndex = 8; // // menuStrip @@ -128,31 +103,22 @@ this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Padding = new System.Windows.Forms.Padding(6, 3, 0, 3); - this.menuStrip.Size = new System.Drawing.Size(1441, 30); - this.menuStrip.Size = new System.Drawing.Size(1259, 30); + this.menuStrip.Size = new System.Drawing.Size(1433, 30); this.menuStrip.TabIndex = 7; this.menuStrip.Text = "Справочники"; // // справочникиToolStripMenuItem // this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.клиентыToolStripMenuItem, this.компонентыToolStripMenuItem, this.мороженоеToolStripMenuItem, this.клиентыToolStripMenuItem, - this.ImplementersToolStripMenuItem}); + this.ImplementersToolStripMenuItem, this.магазиныToolStripMenuItem}); this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24); this.справочникиToolStripMenuItem.Text = "Справочники"; // - // клиентыToolStripMenuItem - // - this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(224, 26); - this.клиентыToolStripMenuItem.Text = "Клиенты"; - this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click); - // // компонентыToolStripMenuItem // this.компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; @@ -184,7 +150,7 @@ // магазиныToolStripMenuItem // this.магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; - this.магазиныToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.магазиныToolStripMenuItem.Size = new System.Drawing.Size(185, 26); this.магазиныToolStripMenuItem.Text = "Магазины"; this.магазиныToolStripMenuItem.Click += new System.EventHandler(this.магазиныToolStripMenuItem_Click); // @@ -222,7 +188,6 @@ this.ordersToolStripMenuItem.Text = "Список заказов"; this.ordersToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click); // - // DoWorkToolStripMenuItem // listShopsToolStripMenuItem // this.listShopsToolStripMenuItem.Name = "listShopsToolStripMenuItem"; @@ -244,9 +209,16 @@ this.ordersByDateToolStripMenuItem.Text = "Заказы по дате"; this.ordersByDateToolStripMenuItem.Click += new System.EventHandler(this.ordersByDateToolStripMenuItem_Click); // + // DoWorkToolStripMenuItem + // + this.DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem"; + this.DoWorkToolStripMenuItem.Size = new System.Drawing.Size(114, 24); + this.DoWorkToolStripMenuItem.Text = "Запуск работ"; + this.DoWorkToolStripMenuItem.Click += new System.EventHandler(this.DoWorkToolStripMenuItem_Click); + // // buttonSupplyShop // - this.buttonSupplyShop.Location = new System.Drawing.Point(1053, 290); + this.buttonSupplyShop.Location = new System.Drawing.Point(1231, 292); this.buttonSupplyShop.Name = "buttonSupplyShop"; this.buttonSupplyShop.Size = new System.Drawing.Size(194, 44); this.buttonSupplyShop.TabIndex = 14; @@ -256,11 +228,7 @@ // // SellIceCreamButton // - this.DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem"; - this.DoWorkToolStripMenuItem.Size = new System.Drawing.Size(114, 24); - this.DoWorkToolStripMenuItem.Text = "Запуск работ"; - this.DoWorkToolStripMenuItem.Click += new System.EventHandler(this.DoWorkToolStripMenuItem_Click); - this.SellIceCreamButton.Location = new System.Drawing.Point(1053, 246); + this.SellIceCreamButton.Location = new System.Drawing.Point(1231, 248); this.SellIceCreamButton.Name = "SellIceCreamButton"; this.SellIceCreamButton.Size = new System.Drawing.Size(194, 40); this.SellIceCreamButton.TabIndex = 15; @@ -272,8 +240,7 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1441, 463); - this.ClientSize = new System.Drawing.Size(1259, 467); + this.ClientSize = new System.Drawing.Size(1433, 467); this.Controls.Add(this.SellIceCreamButton); this.Controls.Add(this.buttonSupplyShop); this.Controls.Add(this.buttonUpdate); diff --git a/IceCreamShop/IceCreamShop/FormMain.cs b/IceCreamShop/IceCreamShop/FormMain.cs index f900f5e..4d6f9f6 100644 --- a/IceCreamShop/IceCreamShop/FormMain.cs +++ b/IceCreamShop/IceCreamShop/FormMain.cs @@ -95,59 +95,6 @@ namespace IceCreamShopView } } - private void buttonSetToWork_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 buttonSetToDone_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.DeliveryOrder(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 buttonSetToFinish_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs index bffe5c3..b86ef7a 100644 --- a/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs @@ -19,5 +19,7 @@ namespace IceCreamShopContracts.BusinessLogicsContracts bool Delete(ShopBindingModel model); bool SupplyIceCreams(ShopSearchModel model, IIceCreamModel iceCream, int count); bool SellIceCreams(IIceCreamModel iceCream, int count); + bool AddIceCream(IIceCreamModel icecream, int count); + int GetFreePlaces(int countIceCreams); } } diff --git a/IceCreamShop/IceCreamShopDataModels/Enums/OrderStatus.cs b/IceCreamShop/IceCreamShopDataModels/Enums/OrderStatus.cs index 5c22c79..e7e6adc 100644 --- a/IceCreamShop/IceCreamShopDataModels/Enums/OrderStatus.cs +++ b/IceCreamShop/IceCreamShopDataModels/Enums/OrderStatus.cs @@ -6,6 +6,7 @@ Принят = 0, Выполняется = 1, Готов = 2, - Выдан = 3 + Выдан = 3, + Ожидается = 4 } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Implements/OrderStorage.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Implements/OrderStorage.cs index c657526..b38b9b4 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Implements/OrderStorage.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Implements/OrderStorage.cs @@ -114,7 +114,7 @@ namespace IceCreamShopDatabaseImplement.Implements } order.Update(model); context.SaveChanges(); - return context.Orders.Include(x => x.IceCream).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return order.GetViewModel; } } } diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs index 3369a3d..8afb064 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs @@ -238,7 +238,7 @@ namespace IceCreamShopDatabaseImplement.Migrations b.HasIndex("ShopId"); - b.ToTable("IceCreams"); + b.ToTable("ShopIcecreams"); }); modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.IceCreamComponent", b => @@ -274,16 +274,15 @@ namespace IceCreamShopDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.Navigation("IceCream"); - }); - - modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => - { - b.HasOne("IceCreamShopDatabaseImplement.Models.IceCream", null) + b.HasOne("IceCreamShopDatabaseImplement.Models.Implementer", "Implementer") .WithMany("Orders") - .HasForeignKey("IceCreamId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("IceCream"); + + b.Navigation("Implementer"); }); modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b => @@ -301,22 +300,14 @@ namespace IceCreamShopDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("IceCreamShopDatabaseImplement.Models.Implementer", "Implementer") - .WithMany("Orders") - .HasForeignKey("ImplementerId"); - b.HasOne("IceCreamShopDatabaseImplement.Models.Shop", "Shop") .WithMany("IceCreams") .HasForeignKey("ShopId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.Navigation("Client"); - b.Navigation("IceCream"); - b.Navigation("Implementer"); - b.Navigation("Shop"); }); @@ -335,13 +326,13 @@ namespace IceCreamShopDatabaseImplement.Migrations b.Navigation("Components"); b.Navigation("Orders"); + + b.Navigation("Shops"); }); modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Implementer", b => { b.Navigation("Orders"); - - b.Navigation("Shops"); }); modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b => diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Order.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Order.cs index 4568883..9180665 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Order.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Order.cs @@ -77,7 +77,7 @@ namespace IceCreamShopDatabaseImplement.Models DateImplement = DateImplement, Id = Id, IceCreamName = context.IceCreams.FirstOrDefault(x => x.Id == IceCreamId)?.IceCreamName ?? string.Empty, - ImplementerFIO = context.Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty, + ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty, ClientFIO = Client?.ClientFIO ?? string.Empty, }; } diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs index 8143f85..3c5eff6 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs @@ -25,7 +25,7 @@ namespace IceCreamShopDatabaseImplement.Models { get { - if(_cashedIcecreams == null) + if (_cashedIcecreams == null) { _cashedIcecreams = IceCreams.ToDictionary(recPC => recPC.IceCreamId, recPC => (recPC.IceCream as IIceCreamModel, recPC.Count)); } @@ -56,7 +56,7 @@ namespace IceCreamShopDatabaseImplement.Models IceCreamMaxCount = model.IceCreamMaxCount, IceCreams = model.ShopIceCreams.Select(x => new ShopIcecream { - IceCream = context.IceCreams.First(y => y.Id == x.Key)!, + IceCream = context.IceCreams.FirstOrDefault(y => y.Id == x.Key)!, Count = x.Value.Item2, }).ToList() }; @@ -70,7 +70,6 @@ namespace IceCreamShopDatabaseImplement.Models Name = model.Name; Adress = model.Adress; OpeningDate = model.OpeningDate; - IceCreamMaxCount = model.IceCreamMaxCount; } public ShopViewModel GetViewModel => new() { @@ -84,36 +83,30 @@ namespace IceCreamShopDatabaseImplement.Models public void UpdateIceCreams(IceCreamShopDatabase context, ShopBindingModel model) { - if (model.ShopIceCreams == null) return; - var iceCreams = context.ShopIcecreams.Where(rec => rec.ShopId == model.Id).ToList(); - if (iceCreams != null && iceCreams.Count > 0) - { - // удалили те, которых нет в модели - if (shopIcecreams != null && shopIcecreams.Count > 0) + var shopIceCreams = context.ShopIcecreams + .Where(rec => rec.ShopId == model.Id) + .ToList(); + // удалили те, которых нет в модели + if (shopIceCreams != null && shopIceCreams.Count > 0) { context.ShopIcecreams - .RemoveRange(shopIcecreams + .RemoveRange(shopIceCreams .Where(rec => !model.ShopIceCreams .ContainsKey(rec.IceCreamId))); // обновили количество у существующих записей - foreach (var updateIceCream in iceCreams) + foreach (var updateIcecream in shopIceCreams.Where(x => model.ShopIceCreams.ContainsKey(x.IceCreamId))) { - updateIceCream.Count = model.ShopIceCreams[updateIceCream.IceCreamId].Item2; - model.ShopIceCreams.Remove(updateIceCream.IceCreamId); + updateIcecream.Count = model.ShopIceCreams[updateIcecream.IceCreamId].Item2; + model.ShopIceCreams.Remove(updateIcecream.IceCreamId); } - context.SaveChanges(); } - var shop = context.Shops.First(x => x.Id == Id); - foreach (var elem in model.ShopIceCreams) + var shop = context.Shops.First(x => x.Id == model.Id); + shop.IceCreams.AddRange(model.ShopIceCreams.Select(x => new ShopIcecream { - context.ShopIcecreams.Add(new ShopIcecream - { - Shop = shop, - IceCream = context.IceCreams.First(x => x.Id == elem.Key), - Count = elem.Value.Item2 - }); - context.SaveChanges(); - } + IceCream = context.IceCreams.First(y => y.Id == x.Key), + Count = x.Value.Item2, + }).Except(shopIceCreams ?? new())); + context.SaveChanges(); _cashedIcecreams = null; } }