diff --git a/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs b/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs index 88c9961..a499e3a 100644 --- a/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs +++ b/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs @@ -74,41 +74,48 @@ namespace ComputersShopFileImplement.Implements public bool SellComputers(IComputerModel model, int quantity) { - int availableQuantity = source.Shops.Select(x => x.Computers.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum(); - if (availableQuantity < quantity) - { - return false; - } - var shops = source.Shops.Where(x => x.Computers.ContainsKey(model.Id)); - foreach (var shop in shops) - { - int countInCurrentShop = shop.Computers[model.Id].Item2; - if (countInCurrentShop <= quantity) - { - shop.Computers[model.Id] = (shop.Computers[model.Id].Item1, 0); - quantity -= countInCurrentShop; - } - else - { - shop.Computers[model.Id] = (shop.Computers[model.Id].Item1, countInCurrentShop - quantity); - quantity = 0; - } - Update(new ShopBindingModel - { - Id = shop.Id, - ShopName = shop.ShopName, - ShopAddress = shop.ShopAddress, - DateOpening = shop.DateOpening, - Computers = shop.Computers, - Capacity = shop.Capacity - }); - if (quantity == 0) - { - return true; - } - } - return false; - } + int hasCount = 0; + + source.Shops.ForEach(x => + { + if (x.Computers.TryGetValue(model.Id, out var pair)) + { + hasCount += pair.Item2; + } + }); + + if (hasCount < quantity) return false; + + source.Shops.ForEach(x => + { + if (x.Computers.TryGetValue(model.Id, out var pair)) + { + if (quantity >= pair.Item2) + { + quantity -= pair.Item2; + x.Computers[model.Id] = (model, 0); + } + else + { + x.Computers[model.Id] = (model, pair.Item2 - quantity); + quantity = 0; + } + + x.Update(new ShopBindingModel + { + Id = x.Id, + ShopAddress = x.ShopAddress, + Capacity = x.Capacity, + DateOpening = x.DateOpening, + ShopName = x.ShopName, + Computers = x.Computers + }); + } + }); + + source.SaveShops(); + return true; + } public ShopViewModel? Update(ShopBindingModel model) { diff --git a/ComputersShop/ComputersShopView/FormSellComputers.cs b/ComputersShop/ComputersShopView/FormSellComputers.cs index 323ff81..e301cec 100644 --- a/ComputersShop/ComputersShopView/FormSellComputers.cs +++ b/ComputersShop/ComputersShopView/FormSellComputers.cs @@ -39,7 +39,7 @@ namespace ComputersShopView { if (comboBoxDocuments.SelectedValue == null) { - MessageBox.Show("Выберите корабль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите компьютер", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(numericUpDownCount.Text))