From ea5ba3cf1b43693dae603cad86f9e0bd0d6a866e Mon Sep 17 00:00:00 2001 From: Salikh Date: Sat, 23 Mar 2024 02:05:58 +0400 Subject: [PATCH 01/13] FirstCommit --- MotorPlant/MotorPlant.sln | 10 +- .../BusinessLogic/ShopLogic.cs | 156 ++++++++++++++ .../BindingModels/ShopBindingModel.cs | 18 ++ .../BusinessLogicsContracts/IShopLogic.cs | 22 ++ .../SearchModels/ShopSearchModel.cs | 14 ++ .../StoragesContracts/IShopStorage.cs | 21 ++ .../ViewModels/ShopViewModel.cs | 29 +++ .../MotorPlantDataModels/Models/IShopModel.cs | 15 ++ .../DataListSingleton.cs | 3 + .../Implements/ShopStorage.cs | 107 ++++++++++ .../MotorPlantListImplement/Models/Shop.cs | 54 +++++ MotorPlant/MotorPlantView/FormEngines.cs | 10 +- .../MotorPlantView/FormMain.Designer.cs | 63 +++--- MotorPlant/MotorPlantView/FormMain.cs | 20 ++ .../MotorPlantView/FormShop.Designer.cs | 193 ++++++++++++++++++ MotorPlant/MotorPlantView/FormShop.cs | 122 +++++++++++ MotorPlant/MotorPlantView/FormShop.resx | 120 +++++++++++ .../MotorPlantView/FormShops.Designer.cs | 114 +++++++++++ MotorPlant/MotorPlantView/FormShops.cs | 108 ++++++++++ MotorPlant/MotorPlantView/FormShops.resx | 120 +++++++++++ .../MotorPlantView/FormSupply.Designer.cs | 147 +++++++++++++ MotorPlant/MotorPlantView/FormSupply.cs | 140 +++++++++++++ MotorPlant/MotorPlantView/FormSupply.resx | 120 +++++++++++ MotorPlant/MotorPlantView/Program.cs | 8 +- MotorPlant/ShopsForm/Form1.Designer.cs | 39 ++++ MotorPlant/ShopsForm/Form1.cs | 10 + MotorPlant/ShopsForm/Form1.resx | 120 +++++++++++ MotorPlant/ShopsForm/Program.cs | 17 ++ MotorPlant/ShopsForm/ShopsForm.csproj | 11 + 29 files changed, 1894 insertions(+), 37 deletions(-) create mode 100644 MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs create mode 100644 MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs create mode 100644 MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs create mode 100644 MotorPlant/MotorPlantDataModels/Models/IShopModel.cs create mode 100644 MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs create mode 100644 MotorPlant/MotorPlantListImplement/Models/Shop.cs create mode 100644 MotorPlant/MotorPlantView/FormShop.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormShop.cs create mode 100644 MotorPlant/MotorPlantView/FormShop.resx create mode 100644 MotorPlant/MotorPlantView/FormShops.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormShops.cs create mode 100644 MotorPlant/MotorPlantView/FormShops.resx create mode 100644 MotorPlant/MotorPlantView/FormSupply.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormSupply.cs create mode 100644 MotorPlant/MotorPlantView/FormSupply.resx create mode 100644 MotorPlant/ShopsForm/Form1.Designer.cs create mode 100644 MotorPlant/ShopsForm/Form1.cs create mode 100644 MotorPlant/ShopsForm/Form1.resx create mode 100644 MotorPlant/ShopsForm/Program.cs create mode 100644 MotorPlant/ShopsForm/ShopsForm.csproj diff --git a/MotorPlant/MotorPlant.sln b/MotorPlant/MotorPlant.sln index b12bd0e..60fc674 100644 --- a/MotorPlant/MotorPlant.sln +++ b/MotorPlant/MotorPlant.sln @@ -3,15 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.7.34031.279 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantView", "MotorPlantView\MotorPlantView.csproj", "{254164C1-CDF8-4F3C-8564-8C8987B7BFA1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantView", "MotorPlantView\MotorPlantView.csproj", "{254164C1-CDF8-4F3C-8564-8C8987B7BFA1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantDataModels", "MotorPlantDataModels\MotorPlantDataModels.csproj", "{F9D3BBA7-D038-4F69-911E-0A25407E4716}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantDataModels", "MotorPlantDataModels\MotorPlantDataModels.csproj", "{F9D3BBA7-D038-4F69-911E-0A25407E4716}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantContracts", "MotorPlantContracts\MotorPlantContracts.csproj", "{B2784391-936D-471E-BB99-215CB345B1CD}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantContracts", "MotorPlantContracts\MotorPlantContracts.csproj", "{B2784391-936D-471E-BB99-215CB345B1CD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantListImplement", "MotorPlantListImplement\MotorPlantListImplement.csproj", "{0694ECF1-AEF8-4033-A0BF-EAA22A733F31}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantListImplement", "MotorPlantListImplement\MotorPlantListImplement.csproj", "{0694ECF1-AEF8-4033-A0BF-EAA22A733F31}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantBusinessLogic", "MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{75003AA5-9D46-45B6-9EF0-BAF16E2790EA}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantBusinessLogic", "MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{75003AA5-9D46-45B6-9EF0-BAF16E2790EA}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs new file mode 100644 index 0000000..a85fe49 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -0,0 +1,156 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + public ShopLogic(ILogger logger, IShopStorage shopStorage) + { + _logger = logger; + _shopStorage = shopStorage; + } + public List ReadList(ShopSearchModel model) + { + _logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + public ShopViewModel ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Adress)) + { + throw new ArgumentNullException("Нет адресса магазина", + nameof(model.ShopName)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", + nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Adress, model.DateOpen, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + public bool MakeSupply(ShopSearchModel model, IEngineModel dress, int count) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (dress == null) + throw new ArgumentNullException(nameof(dress)); + if (count <= 0) + throw new ArgumentNullException("Количество должно быть положительным числом"); + + ShopViewModel? curModel = _shopStorage.GetElement(model); + _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); + if (curModel.ShopEngines.TryGetValue(dress.Id, out var pair)) + { + curModel.ShopEngines[dress.Id] = (pair.Item1, pair.Item2 + count); + _logger.LogInformation("Make Supply. Add Dress. DressName: {Name}. Count: {Count}", pair.Item1, count + pair.Item2); + } + else + { + curModel.ShopEngines.Add(dress.Id, (dress, count)); + _logger.LogInformation("Make Supply. Add new Dress. DressName: {Name}. Count: {Count}", pair.Item1, count); + } + + return Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + DateOpen = curModel.DateOpen, + Adress = curModel.Adress, + ShopEngines = curModel.ShopEngines, + }); + } + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..855a76f --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,18 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } + public string Adress { get; set; } + public DateTime DateOpen { get; set; } + public Dictionary ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..15e3fc8 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,22 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel? model); + bool Create(ShopBindingModel? model); + bool Update(ShopBindingModel? model); + bool Delete(ShopBindingModel? model); + bool MakeSupply(ShopSearchModel model, IEngineModel dress, int count); + } +} diff --git a/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..470bafb --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? Name { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..48c46db --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,21 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..4cd1610 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,29 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + + [DisplayName("Название магазина")] + + public string ShopName { get; set; } = string.Empty; + + [DisplayName("Адрес")] + + public string Adress { get; set; } = string.Empty; + + [DisplayName("Дата открытия")] + + public DateTime DateOpen { get; set; } + + public Dictionary ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..7552320 --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Adress { get; } + DateTime DateOpen { get; } + } +} diff --git a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs index 4bd61f6..763c235 100644 --- a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs +++ b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs @@ -12,11 +12,14 @@ namespace MotorPlantListImplement public List Engines { get; set; } + public List Shops { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Engines = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..6ba0064 --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -0,0 +1,107 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.Name)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.Name)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.Name) && + shop.ShopName == model.Name) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Models/Shop.cs b/MotorPlant/MotorPlantListImplement/Models/Shop.cs new file mode 100644 index 0000000..ef03e2e --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Models/Shop.cs @@ -0,0 +1,54 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Adress { get; private set; } + public DateTime DateOpen { get; private set; } + public Dictionary ShopEngines { get; private set; } = new(); + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + ShopEngines = new() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + ShopEngines = model.ShopEngines; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + ShopEngines = ShopEngines + }; + } +} diff --git a/MotorPlant/MotorPlantView/FormEngines.cs b/MotorPlant/MotorPlantView/FormEngines.cs index 7e129dc..d686eec 100644 --- a/MotorPlant/MotorPlantView/FormEngines.cs +++ b/MotorPlant/MotorPlantView/FormEngines.cs @@ -15,11 +15,6 @@ namespace MotorPlantView.Forms _logic = logic; } - private void FormEngines_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() { try @@ -40,6 +35,11 @@ namespace MotorPlantView.Forms } } + private void FormEngines_Load(object sender, EventArgs e) + { + LoadData(); + } + private void buttonAdd_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormEngine)); diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index 1673d78..33f0712 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -32,6 +32,8 @@ toolStripDropDownButton1 = new ToolStripDropDownButton(); КомпонентыToolStripMenuItem = new ToolStripMenuItem(); ДвигателиToolStripMenuItem = new ToolStripMenuItem(); + ShopsToolStripMenuItem = new ToolStripMenuItem(); + поставкиToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); @@ -48,41 +50,54 @@ toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; - toolStrip1.Size = new Size(1126, 27); + toolStrip1.Size = new Size(985, 25); toolStrip1.TabIndex = 0; toolStrip1.Text = "toolStrip1"; // // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, ShopsToolStripMenuItem, поставкиToolStripMenuItem }); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new Size(108, 24); + toolStripDropDownButton1.Size = new Size(88, 22); toolStripDropDownButton1.Text = "Справочник"; // // КомпонентыToolStripMenuItem // КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; - КомпонентыToolStripMenuItem.Size = new Size(224, 26); + КомпонентыToolStripMenuItem.Size = new Size(180, 22); КомпонентыToolStripMenuItem.Text = "Компоненты"; КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; // // ДвигателиToolStripMenuItem // ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; - ДвигателиToolStripMenuItem.Size = new Size(224, 26); + ДвигателиToolStripMenuItem.Size = new Size(180, 22); ДвигателиToolStripMenuItem.Text = "Двигатели"; ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // + // ShopsToolStripMenuItem + // + ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; + ShopsToolStripMenuItem.Size = new Size(180, 22); + ShopsToolStripMenuItem.Text = "Магазины"; + ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + // + // поставкиToolStripMenuItem + // + поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; + поставкиToolStripMenuItem.Size = new Size(180, 22); + поставкиToolStripMenuItem.Text = "Поставки"; + поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonCreateOrder.BackColor = SystemColors.ControlLight; - buttonCreateOrder.Location = new Point(911, 195); - buttonCreateOrder.Margin = new Padding(3, 4, 3, 4); + buttonCreateOrder.Location = new Point(797, 146); buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(203, 40); + buttonCreateOrder.Size = new Size(178, 30); buttonCreateOrder.TabIndex = 1; buttonCreateOrder.Text = "Создать заказ"; buttonCreateOrder.UseVisualStyleBackColor = false; @@ -92,10 +107,9 @@ // buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; - buttonTakeOrderInWork.Location = new Point(911, 258); - buttonTakeOrderInWork.Margin = new Padding(3, 4, 3, 4); + buttonTakeOrderInWork.Location = new Point(797, 194); buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(203, 40); + buttonTakeOrderInWork.Size = new Size(178, 30); buttonTakeOrderInWork.TabIndex = 2; buttonTakeOrderInWork.Text = "Отдать на выполнение"; buttonTakeOrderInWork.UseVisualStyleBackColor = false; @@ -105,10 +119,9 @@ // buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonOrderReady.BackColor = SystemColors.ControlLight; - buttonOrderReady.Location = new Point(911, 323); - buttonOrderReady.Margin = new Padding(3, 4, 3, 4); + buttonOrderReady.Location = new Point(797, 242); buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(203, 40); + buttonOrderReady.Size = new Size(178, 30); buttonOrderReady.TabIndex = 3; buttonOrderReady.Text = "Заказ готов"; buttonOrderReady.UseVisualStyleBackColor = false; @@ -118,10 +131,9 @@ // buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonIssuedOrder.BackColor = SystemColors.ControlLight; - buttonIssuedOrder.Location = new Point(911, 383); - buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4); + buttonIssuedOrder.Location = new Point(797, 287); buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(203, 40); + buttonIssuedOrder.Size = new Size(178, 30); buttonIssuedOrder.TabIndex = 4; buttonIssuedOrder.Text = "Заказ выдан"; buttonIssuedOrder.UseVisualStyleBackColor = false; @@ -131,10 +143,9 @@ // buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonRef.BackColor = SystemColors.ControlLight; - buttonRef.Location = new Point(911, 133); - buttonRef.Margin = new Padding(3, 4, 3, 4); + buttonRef.Location = new Point(797, 100); buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(203, 40); + buttonRef.Size = new Size(178, 30); buttonRef.TabIndex = 5; buttonRef.Text = "Обновить список"; buttonRef.UseVisualStyleBackColor = false; @@ -145,21 +156,20 @@ dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; dataGridView.BackgroundColor = SystemColors.ButtonHighlight; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 35); - dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Location = new Point(11, 28); dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 24; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(891, 588); + dataGridView.Size = new Size(780, 441); dataGridView.TabIndex = 6; // // FormMain // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1126, 623); + ClientSize = new Size(985, 467); Controls.Add(dataGridView); Controls.Add(buttonRef); Controls.Add(buttonIssuedOrder); @@ -167,7 +177,6 @@ Controls.Add(buttonTakeOrderInWork); Controls.Add(buttonCreateOrder); Controls.Add(toolStrip1); - Margin = new Padding(3, 4, 3, 4); Name = "FormMain"; Text = "Моторный завод"; Load += FormMain_Load; @@ -190,5 +199,7 @@ private ToolStripDropDownButton toolStripDropDownButton1; private ToolStripMenuItem КомпонентыToolStripMenuItem; private ToolStripMenuItem ДвигателиToolStripMenuItem; + private ToolStripMenuItem ShopsToolStripMenuItem; + private ToolStripMenuItem поставкиToolStripMenuItem; } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index 06f7132..3172e11 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantView; namespace MotorPlantView.Forms { @@ -143,5 +144,24 @@ namespace MotorPlantView.Forms { LoadData(); } + private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + + if (service is FormSupply form) + { + form.ShowDialog(); + } + } } } diff --git a/MotorPlant/MotorPlantView/FormShop.Designer.cs b/MotorPlant/MotorPlantView/FormShop.Designer.cs new file mode 100644 index 0000000..9e574fc --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.Designer.cs @@ -0,0 +1,193 @@ +namespace MotorPlantView +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + dateTimePicker = new DateTimePicker(); + textBoxName = new TextBox(); + textBoxAdress = new TextBox(); + dataGridView = new DataGridView(); + IdColumn = new DataGridViewTextBoxColumn(); + Title = new DataGridViewTextBoxColumn(); + Cost = new DataGridViewTextBoxColumn(); + Count = new DataGridViewTextBoxColumn(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dateTimePicker + // + dateTimePicker.Location = new Point(714, 34); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(250, 27); + dateTimePicker.TabIndex = 0; + // + // textBoxName + // + textBoxName.Location = new Point(714, 85); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(250, 27); + textBoxName.TabIndex = 1; + // + // textBoxAdress + // + textBoxAdress.Location = new Point(714, 139); + textBoxAdress.Name = "textBoxAdress"; + textBoxAdress.Size = new Size(250, 27); + textBoxAdress.TabIndex = 2; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { IdColumn, Title, Cost, Count }); + dataGridView.Location = new Point(10, 32); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(554, 380); + dataGridView.TabIndex = 3; + // + // IdColumn + // + IdColumn.HeaderText = "Номер платья"; + IdColumn.MinimumWidth = 6; + IdColumn.Name = "IdColumn"; + IdColumn.Visible = false; + IdColumn.Width = 125; + // + // Title + // + Title.HeaderText = "Название"; + Title.MinimumWidth = 6; + Title.Name = "Title"; + Title.Width = 125; + // + // Cost + // + Cost.HeaderText = "Цена"; + Cost.MinimumWidth = 6; + Cost.Name = "Cost"; + Cost.Width = 125; + // + // Count + // + Count.HeaderText = "Количество"; + Count.MinimumWidth = 6; + Count.Name = "Count"; + Count.Width = 125; + // + // buttonSave + // + buttonSave.Location = new Point(714, 219); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(94, 29); + buttonSave.TabIndex = 4; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(870, 219); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(94, 29); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(592, 39); + label1.Name = "label1"; + label1.Size = new Size(110, 20); + label1.TabIndex = 6; + label1.Text = "Дата создания"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(592, 88); + label2.Name = "label2"; + label2.Size = new Size(77, 20); + label2.TabIndex = 7; + label2.Text = "Название"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(592, 142); + label3.Name = "label3"; + label3.Size = new Size(51, 20); + label3.TabIndex = 8; + label3.Text = "Адрес"; + // + // ShopForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(976, 450); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(dataGridView); + Controls.Add(textBoxAdress); + Controls.Add(textBoxName); + Controls.Add(dateTimePicker); + Name = "ShopForm"; + Text = "Форма магазина"; + Load += ShopForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePicker; + private TextBox textBoxName; + private TextBox textBoxAdress; + private DataGridView dataGridView; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + private Label label3; + private DataGridViewTextBoxColumn IdColumn; + private DataGridViewTextBoxColumn Title; + private DataGridViewTextBoxColumn Cost; + private DataGridViewTextBoxColumn Count; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShop.cs b/MotorPlant/MotorPlantView/FormShop.cs new file mode 100644 index 0000000..a408e09 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.cs @@ -0,0 +1,122 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public int? _id; + private Dictionary _engine; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ShopForm_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Shop load"); + try + { + var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); + if (shop != null) + { + textBoxName.Text = shop.ShopName; + textBoxAdress.Text = shop.Adress; + dateTimePicker.Text = shop.DateOpen.ToString(); + _engine = shop.ShopEngines; + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Load engines"); + try + { + if (_engine != null) + { + foreach (var dress in _engine) + { + dataGridView.Rows.Add(new object[] { dress.Key, dress.Value.Item1.EngineName, dress.Value.Item1.Price, dress.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Load engines into shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Save shop"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + DateOpen = dateTimePicker.Value.Date, + ShopEngines = _engine + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Save shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormShop.resx b/MotorPlant/MotorPlantView/FormShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShops.Designer.cs b/MotorPlant/MotorPlantView/FormShops.Designer.cs new file mode 100644 index 0000000..b4d34e3 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.Designer.cs @@ -0,0 +1,114 @@ +namespace MotorPlantView +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonReset = new Button(); + buttonDelete = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(617, 426); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(665, 114); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(123, 45); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(665, 165); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(123, 44); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonReset + // + buttonReset.Location = new Point(665, 215); + buttonReset.Name = "buttonReset"; + buttonReset.Size = new Size(123, 48); + buttonReset.TabIndex = 3; + buttonReset.Text = "Обновить"; + buttonReset.UseVisualStyleBackColor = true; + buttonReset.Click += buttonReset_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(665, 269); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(123, 48); + buttonDelete.TabIndex = 4; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(buttonDelete); + Controls.Add(buttonReset); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormShops"; + Text = "FormShops"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonReset; + private Button buttonDelete; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShops.cs b/MotorPlant/MotorPlantView/FormShops.cs new file mode 100644 index 0000000..8a4cbcb --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.cs @@ -0,0 +1,108 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantView.Forms; + +namespace MotorPlantView +{ + public partial class FormShops : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public FormShops(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["Adress"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ShopEngines"].Visible = false; + } + _logger.LogInformation("Load shops"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + form._id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void buttonReset_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormShops.resx b/MotorPlant/MotorPlantView/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSupply.Designer.cs b/MotorPlant/MotorPlantView/FormSupply.Designer.cs new file mode 100644 index 0000000..1b5719f --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.Designer.cs @@ -0,0 +1,147 @@ +namespace MotorPlantView +{ + partial class FormSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + ShopComboBox = new ComboBox(); + EngineComboBox = new ComboBox(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + Cancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + SuspendLayout(); + // + // ShopComboBox + // + ShopComboBox.FormattingEnabled = true; + ShopComboBox.Location = new Point(136, 26); + ShopComboBox.Margin = new Padding(3, 2, 3, 2); + ShopComboBox.Name = "ShopComboBox"; + ShopComboBox.Size = new Size(279, 23); + ShopComboBox.TabIndex = 0; + // + // EngineComboBox + // + EngineComboBox.FormattingEnabled = true; + EngineComboBox.Location = new Point(136, 59); + EngineComboBox.Margin = new Padding(3, 2, 3, 2); + EngineComboBox.Name = "EngineComboBox"; + EngineComboBox.Size = new Size(279, 23); + EngineComboBox.TabIndex = 1; + // + // CountTextBox + // + CountTextBox.Location = new Point(136, 96); + CountTextBox.Margin = new Padding(3, 2, 3, 2); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(279, 23); + CountTextBox.TabIndex = 2; + // + // SaveButton + // + SaveButton.Location = new Point(220, 150); + SaveButton.Margin = new Padding(3, 2, 3, 2); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(94, 27); + SaveButton.TabIndex = 3; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // Cancel + // + Cancel.Location = new Point(319, 150); + Cancel.Margin = new Padding(3, 2, 3, 2); + Cancel.Name = "Cancel"; + Cancel.Size = new Size(94, 27); + Cancel.TabIndex = 4; + Cancel.Text = "Отмена"; + Cancel.UseVisualStyleBackColor = true; + Cancel.Click += CancelButton_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(35, 28); + label1.Name = "label1"; + label1.Size = new Size(54, 15); + label1.TabIndex = 5; + label1.Text = "Магазин"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(35, 62); + label2.Name = "label2"; + label2.Size = new Size(64, 15); + label2.TabIndex = 6; + label2.Text = "Двигатели"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(35, 98); + label3.Name = "label3"; + label3.Size = new Size(72, 15); + label3.TabIndex = 7; + label3.Text = "Количество"; + // + // FormSupply + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(443, 195); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(Cancel); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(EngineComboBox); + Controls.Add(ShopComboBox); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSupply"; + Text = "Форма поставки"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ShopComboBox; + private ComboBox EngineComboBox; + private TextBox CountTextBox; + private Button SaveButton; + private Button Cancel; + private Label label1; + private Label label2; + private Label label3; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSupply.cs b/MotorPlant/MotorPlantView/FormSupply.cs new file mode 100644 index 0000000..fa59e52 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.cs @@ -0,0 +1,140 @@ +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; + +namespace MotorPlantView +{ + public partial class FormSupply : Form + { + private readonly List? _engineList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IEngineLogic _engineLogic; + public int ShopId + { + get + { + return Convert.ToInt32(ShopComboBox.SelectedValue); + } + set + { + ShopComboBox.SelectedValue = value; + } + } + public int EngineId + { + get + { + return Convert.ToInt32(EngineComboBox.SelectedValue); + } + set + { + EngineComboBox.SelectedValue = value; + } + } + + public IEngineModel? EngineModel + { + get + { + if (_engineList == null) + { + return null; + } + foreach (var elem in _engineList) + { + if (elem.Id == EngineId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + public FormSupply(IEngineLogic engineLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _engineLogic = engineLogic; + _engineList = engineLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_engineList != null) + { + EngineComboBox.DisplayMember = "EngineName"; + EngineComboBox.ValueMember = "Id"; + EngineComboBox.DataSource = _engineList; + EngineComboBox.SelectedItem = null; + } + if (_shopsList != null) + { + ShopComboBox.DisplayMember = "ShopName"; + ShopComboBox.ValueMember = "Id"; + ShopComboBox.DataSource = _shopsList; + ShopComboBox.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (EngineComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите двигатель", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (ShopComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + + bool res = _shopLogic.MakeSupply( + new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, + _engineLogic.ReadElement(new() { Id = Convert.ToInt32(EngineComboBox.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + } + + MessageBox.Show("Пополнение прошло успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception er) + { + MessageBox.Show("Ошибка пополнения"); + return; + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormSupply.resx b/MotorPlant/MotorPlantView/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index 21b1eff..7f64bee 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -6,7 +6,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using MotorPlantBusinessLogic.BusinessLogics; -using System; +using MotorPlantBusinessLogic.BusinessLogic; +using MotorPlantView; namespace MotorPlantView { @@ -42,6 +43,8 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -49,6 +52,9 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Form1.Designer.cs b/MotorPlant/ShopsForm/Form1.Designer.cs new file mode 100644 index 0000000..a8b8dd9 --- /dev/null +++ b/MotorPlant/ShopsForm/Form1.Designer.cs @@ -0,0 +1,39 @@ +namespace ShopsForm +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + this.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Form1.cs b/MotorPlant/ShopsForm/Form1.cs new file mode 100644 index 0000000..6be30b4 --- /dev/null +++ b/MotorPlant/ShopsForm/Form1.cs @@ -0,0 +1,10 @@ +namespace ShopsForm +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Form1.resx b/MotorPlant/ShopsForm/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/ShopsForm/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Program.cs b/MotorPlant/ShopsForm/Program.cs new file mode 100644 index 0000000..4b3f120 --- /dev/null +++ b/MotorPlant/ShopsForm/Program.cs @@ -0,0 +1,17 @@ +namespace ShopsForm +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/MotorPlant/ShopsForm/ShopsForm.csproj b/MotorPlant/ShopsForm/ShopsForm.csproj new file mode 100644 index 0000000..b57c89e --- /dev/null +++ b/MotorPlant/ShopsForm/ShopsForm.csproj @@ -0,0 +1,11 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + \ No newline at end of file From 071e0a01fc0b89772d647f512f3798b340cd85ae Mon Sep 17 00:00:00 2001 From: Salikh Date: Wed, 3 Apr 2024 14:12:16 +0400 Subject: [PATCH 02/13] commit --- .../BusinessLogic/ShopLogic.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs index a85fe49..479e5c3 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -119,12 +119,12 @@ namespace MotorPlantBusinessLogic.BusinessLogic throw new InvalidOperationException("Магазин с таким названием уже есть"); } } - public bool MakeSupply(ShopSearchModel model, IEngineModel dress, int count) + public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) { if (model == null) throw new ArgumentNullException(nameof(model)); - if (dress == null) - throw new ArgumentNullException(nameof(dress)); + if (engine == null) + throw new ArgumentNullException(nameof(engine)); if (count <= 0) throw new ArgumentNullException("Количество должно быть положительным числом"); @@ -132,15 +132,15 @@ namespace MotorPlantBusinessLogic.BusinessLogic _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); if (curModel == null) throw new ArgumentNullException(nameof(curModel)); - if (curModel.ShopEngines.TryGetValue(dress.Id, out var pair)) + if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) { - curModel.ShopEngines[dress.Id] = (pair.Item1, pair.Item2 + count); - _logger.LogInformation("Make Supply. Add Dress. DressName: {Name}. Count: {Count}", pair.Item1, count + pair.Item2); + curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); + _logger.LogInformation("Make Supply. Add Engine. EngineName: {Name}. Count: {Count}", pair.Item1, count + pair.Item2); } else { - curModel.ShopEngines.Add(dress.Id, (dress, count)); - _logger.LogInformation("Make Supply. Add new Dress. DressName: {Name}. Count: {Count}", pair.Item1, count); + curModel.ShopEngines.Add(engine.Id, (engine, count)); + _logger.LogInformation("Make Supply. Add new Engine. EngineName: {Name}. Count: {Count}", pair.Item1, count); } return Update(new() From a528263511b4511626c5e295c742db446f9b4578 Mon Sep 17 00:00:00 2001 From: Salikh Date: Wed, 3 Apr 2024 15:50:05 +0400 Subject: [PATCH 03/13] commit --- .../MotorPlantFileImplement/Implements/OrderStorage.cs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs index 3bb7e5b..d79a83b 100644 --- a/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs @@ -83,14 +83,8 @@ namespace MotorPlantFileImplement.Implements private OrderViewModel GetViewModel(Order order) { var viewModel = order.GetViewModel; - foreach (var comp in source.Engines) - { - if (comp.Id == order.EngineId) - { - viewModel.EngineName = comp.EngineName; - break; - } - } + var engine = source.Engines.FirstOrDefault(x => x.Id == order.EngineId); + viewModel.EngineName = engine?.EngineName; return viewModel; } } From b569dbb44587a28827065624c3c09d5876460d6a Mon Sep 17 00:00:00 2001 From: Salikh Date: Wed, 3 Apr 2024 15:57:18 +0400 Subject: [PATCH 04/13] commit2 --- MotorPlant/MotorPlantFileImplement/Models/Engine.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs index 47f3f3c..e00f328 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs @@ -7,7 +7,7 @@ namespace MotorPlantFileImplement.Models { public class Engine : IEngineModel { - public int Id { get; private set; } + public int Id { get; private set; } public string EngineName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); From e2f57f08a74ab1443ee8c9227f34ea681f9802e6 Mon Sep 17 00:00:00 2001 From: Salikh Date: Wed, 3 Apr 2024 16:02:34 +0400 Subject: [PATCH 05/13] finalycommit --- MotorPlant/MotorPlantListImplement/Models/Order.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/MotorPlant/MotorPlantListImplement/Models/Order.cs b/MotorPlant/MotorPlantListImplement/Models/Order.cs index 56053d1..e8196ac 100644 --- a/MotorPlant/MotorPlantListImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantListImplement/Models/Order.cs @@ -49,12 +49,7 @@ namespace MotorPlantListImplement.Models { return; } - Id = model.Id; - EngineId = model.EngineId; - Count = model.Count; - Sum = model.Sum; Status = model.Status; - DateCreate = model.DateCreate; DateImplement = model.DateImplement; } public OrderViewModel GetViewModel => new() From 08d3fb0189285136ee1766c9508b7ff44aa0c269 Mon Sep 17 00:00:00 2001 From: Salikh Date: Thu, 4 Apr 2024 03:01:18 +0400 Subject: [PATCH 06/13] definitely commit --- ...ion.Designer.cs => 20240403225731_InitMigration.Designer.cs} | 2 +- ...3125759_InitMigration.cs => 20240403225731_InitMigration.cs} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240403125759_InitMigration.Designer.cs => 20240403225731_InitMigration.Designer.cs} (99%) rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240403125759_InitMigration.cs => 20240403225731_InitMigration.cs} (100%) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403125759_InitMigration.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.Designer.cs similarity index 99% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403125759_InitMigration.Designer.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.Designer.cs index 681748f..575ec39 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403125759_InitMigration.Designer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.Designer.cs @@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { [DbContext(typeof(MotorPlantDatabase))] - [Migration("20240403125759_InitMigration")] + [Migration("20240403225731_InitMigration")] partial class InitMigration { /// diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403125759_InitMigration.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.cs similarity index 100% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403125759_InitMigration.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.cs From acc8780b884f05b5c90cbb8bcf0ee65e5a694332 Mon Sep 17 00:00:00 2001 From: Salikh Date: Sun, 7 Apr 2024 01:08:29 +0400 Subject: [PATCH 07/13] final commit --- .../BusinessLogicsContracts/IShopLogic.cs | 2 +- MotorPlant/MotorPlantListImplement/Models/Order.cs | 5 ----- MotorPlant/MotorPlantView/FormEngines.cs | 3 ++- MotorPlant/MotorPlantView/FormShop.cs | 4 ++-- 4 files changed, 5 insertions(+), 9 deletions(-) diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs index 15e3fc8..919d97f 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -17,6 +17,6 @@ namespace MotorPlantContracts.BusinessLogicsContracts bool Create(ShopBindingModel? model); bool Update(ShopBindingModel? model); bool Delete(ShopBindingModel? model); - bool MakeSupply(ShopSearchModel model, IEngineModel dress, int count); + bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); } } diff --git a/MotorPlant/MotorPlantListImplement/Models/Order.cs b/MotorPlant/MotorPlantListImplement/Models/Order.cs index 56053d1..e8196ac 100644 --- a/MotorPlant/MotorPlantListImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantListImplement/Models/Order.cs @@ -49,12 +49,7 @@ namespace MotorPlantListImplement.Models { return; } - Id = model.Id; - EngineId = model.EngineId; - Count = model.Count; - Sum = model.Sum; Status = model.Status; - DateCreate = model.DateCreate; DateImplement = model.DateImplement; } public OrderViewModel GetViewModel => new() diff --git a/MotorPlant/MotorPlantView/FormEngines.cs b/MotorPlant/MotorPlantView/FormEngines.cs index d686eec..0c6692a 100644 --- a/MotorPlant/MotorPlantView/FormEngines.cs +++ b/MotorPlant/MotorPlantView/FormEngines.cs @@ -32,7 +32,8 @@ namespace MotorPlantView.Forms catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки компонентов"); - } + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } private void FormEngines_Load(object sender, EventArgs e) diff --git a/MotorPlant/MotorPlantView/FormShop.cs b/MotorPlant/MotorPlantView/FormShop.cs index a408e09..e1c45bb 100644 --- a/MotorPlant/MotorPlantView/FormShop.cs +++ b/MotorPlant/MotorPlantView/FormShop.cs @@ -61,9 +61,9 @@ namespace MotorPlantView { if (_engine != null) { - foreach (var dress in _engine) + foreach (var engine in _engine) { - dataGridView.Rows.Add(new object[] { dress.Key, dress.Value.Item1.EngineName, dress.Value.Item1.Price, dress.Value.Item2 }); + dataGridView.Rows.Add(new object[] { engine.Key, engine.Value.Item1.EngineName, engine.Value.Item1.Price, engine.Value.Item2 }); } } } From 7772cc65d2cd19457d6008d5889472f4a6cab1f6 Mon Sep 17 00:00:00 2001 From: Salikh Date: Tue, 9 Apr 2024 21:17:41 +0400 Subject: [PATCH 08/13] second commit --- .../BusinessLogic/OrderLogic.cs | 269 +++++++----- .../BusinessLogic/ShopLogic.cs | 144 ++++--- .../BindingModels/ShopBindingModel.cs | 3 +- .../BusinessLogicsContracts/IShopLogic.cs | 3 +- .../StoragesContracts/IShopStorage.cs | 4 +- .../ViewModels/ShopViewModel.cs | 6 +- .../MotorPlantDataModels/Models/IShopModel.cs | 3 +- .../DataFileSingleton.cs | 17 +- .../Implements/ShopStorage .cs | 121 ++++++ .../MotorPlantFileImplement/Models/Shop.cs | 102 +++++ .../Implements/ShopStorage.cs | 11 +- .../MotorPlantListImplement/Models/Shop.cs | 6 +- .../MotorPlantView/FormMain.Designer.cs | 403 +++++++++--------- MotorPlant/MotorPlantView/FormMain.cs | 312 +++++++------- .../MotorPlantView/FormSell.Designer.cs | 122 ++++++ MotorPlant/MotorPlantView/FormSell.cs | 120 ++++++ MotorPlant/MotorPlantView/FormSell.resx | 120 ++++++ .../MotorPlantView/FormShop.Designer.cs | 403 ++++++++++-------- MotorPlant/MotorPlantView/FormShop.cs | 203 ++++----- MotorPlant/MotorPlantView/FormShop.resx | 50 +-- MotorPlant/MotorPlantView/Program.cs | 3 +- 21 files changed, 1580 insertions(+), 845 deletions(-) create mode 100644 MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs create mode 100644 MotorPlant/MotorPlantFileImplement/Models/Shop.cs create mode 100644 MotorPlant/MotorPlantView/FormSell.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormSell.cs create mode 100644 MotorPlant/MotorPlantView/FormSell.resx diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index 7b27063..c3322c1 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -5,128 +5,179 @@ using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; using Microsoft.Extensions.Logging; using MotorPlantDataModels.Enums; +using MotorPlantDataModels.Models; namespace MotorPlantBusinessLogic.BusinessLogics { public class OrderLogic : IOrderLogic { - private readonly ILogger _logger; - private readonly IOrderStorage _orderStorage; + private readonly ILogger _logger; + private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly IShopLogic _shopLogic; + private readonly IEngineStorage _engineStorage; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IEngineStorage engineStorage) + { + _logger = logger; + _orderStorage = orderStorage; + _shopStorage = shopStorage; + _shopLogic = shopLogic; + _engineStorage = engineStorage; + } - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; - _orderStorage = orderStorage; - } + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } - public List? ReadList(OrderSearchModel? model) - { - _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); - var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } + private void CheckModel(OrderBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentNullException("Количество заказов должно быть больше нуля"); + } + if (model.Sum <= 0) + { + throw new ArgumentNullException("Цена заказа должна быть больше нуля"); + } + _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}", model.Id, model.Sum); + } - public bool CreateOrder(OrderBindingModel model) - { - CheckModel(model); + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) + { + return false; + } + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; - if (model.Status != OrderStatus.Неизвестен) - return false; - model.Status = OrderStatus.Принят; + } - if (_orderStorage.Insert(model) == null) - { - model.Status = OrderStatus.Неизвестен; - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + private bool ChangeStatus(OrderBindingModel model, OrderStatus status) + { + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (element == null) + { + _logger.LogWarning("Find order failed"); + return false; + } + if (element.Status != status - 1) + { + _logger.LogWarning("Status change failed"); + throw new InvalidOperationException("Невозможно перевести состояние заказа"); + } + if (status == OrderStatus.Готов) + { + var engine = _engineStorage.GetElement(new EngineSearchModel() { Id = model.EngineId }); + if (engine == null) + { + _logger.LogWarning("Status change error. Engine not found"); + return false; + } + if (!CheckSupply(engine, model.Count)) + { + _logger.LogWarning("Status change error. Shop doesnt have engines"); + return false; + } + } + model.Status = status; + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; + _orderStorage.Update(model); + return true; + } - public bool TakeOrderInWork(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Выполняется); - } + public bool TakeOrderInWork(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } - public bool FinishOrder(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Готов); - } + public bool FinishOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Готов); + } - public bool DeliveryOrder(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Выдан); - } + public bool DeliveryOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выдан); + } - public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + public bool CheckSupply(IEngineModel engine, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check supply operation error. Engine count < 0"); + return false; + } + int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum(); + int sumCount = _shopStorage.GetFullList().Select(x => x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum(); + int free = sumCapacity - sumCount; - model.EngineId = element.EngineId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); - return false; - } - model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; - } - - private void CheckModel(OrderBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (model.Count <= 0) - { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); - } - if (model.Sum <= 0) - { - throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); - } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); - } - _logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id); - } - } + if (free < count) + { + _logger.LogWarning("Check supply error. No place for new Engines"); + return false; + } + foreach (var shop in _shopStorage.GetFullList()) + { + free = shop.MaxCount; + foreach (var doc in shop.ShopEngines) + { + free -= doc.Value.Item2; + } + if (free == 0) + { + continue; + } + if (free >= count) + { + if (_shopLogic.MakeSupply(new() + { + Id = shop.Id + }, engine, count)) + { + count = 0; + } + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + else + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, engine, free)) + count -= free; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } + } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs index 479e5c3..35e65a1 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -17,11 +17,13 @@ namespace MotorPlantBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IShopStorage _shopStorage; + public ShopLogic(ILogger logger, IShopStorage shopStorage) { _logger = logger; _shopStorage = shopStorage; } + public List ReadList(ShopSearchModel model) { _logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); @@ -34,6 +36,7 @@ namespace MotorPlantBusinessLogic.BusinessLogic _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } + public ShopViewModel ReadElement(ShopSearchModel model) { if (model == null) @@ -86,71 +89,86 @@ namespace MotorPlantBusinessLogic.BusinessLogic private void CheckModel(ShopBindingModel model, bool withParams = true) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (string.IsNullOrEmpty(model.ShopName)) - { - throw new ArgumentNullException("Нет названия магазина", - nameof(model.ShopName)); - } - if (string.IsNullOrEmpty(model.Adress)) - { - throw new ArgumentNullException("Нет адресса магазина", - nameof(model.ShopName)); - } - if (model.DateOpen == null) - { - throw new ArgumentNullException("Нет даты открытия магазина", - nameof(model.ShopName)); - } - _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Adress, model.DateOpen, model.Id); - var element = _shopStorage.GetElement(new ShopSearchModel - { - Name = model.ShopName - }); - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Магазин с таким названием уже есть"); - } - } - public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Adress)) + { + throw new ArgumentNullException("Нет адресса магазина", + nameof(model.ShopName)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", + nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Adress, model.DateOpen, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool MakeSell(IEngineModel model, int count) + { + return _shopStorage.SellEngines(model, count); + } + + public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) { - if (model == null) - throw new ArgumentNullException(nameof(model)); - if (engine == null) - throw new ArgumentNullException(nameof(engine)); - if (count <= 0) - throw new ArgumentNullException("Количество должно быть положительным числом"); + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (engine == null) + throw new ArgumentNullException(nameof(engine)); + if (count <= 0) + throw new ArgumentNullException("Количество должно быть положительным числом"); - ShopViewModel? curModel = _shopStorage.GetElement(model); - _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); - if (curModel == null) - throw new ArgumentNullException(nameof(curModel)); - if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) - { - curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); - _logger.LogInformation("Make Supply. Add Engine. EngineName: {Name}. Count: {Count}", pair.Item1, count + pair.Item2); - } - else - { - curModel.ShopEngines.Add(engine.Id, (engine, count)); - _logger.LogInformation("Make Supply. Add new Engine. EngineName: {Name}. Count: {Count}", pair.Item1, count); - } + ShopViewModel? curModel = _shopStorage.GetElement(model); + _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); - return Update(new() - { - Id = curModel.Id, - ShopName = curModel.ShopName, - DateOpen = curModel.DateOpen, - Adress = curModel.Adress, - ShopEngines = curModel.ShopEngines, - }); - } + var countItems = curModel.ShopEngines.Select(x => x.Value.Item2).Sum(); + if (curModel.MaxCount - countItems < count) + { + _logger.LogWarning("Shop is overflowed"); + return false; + } + + if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) + { + curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); + _logger.LogInformation("Make Supply. Add Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count + pair.Item2); + } + else + { + curModel.ShopEngines.Add(engine.Id, (engine, count)); + _logger.LogInformation("Make Supply. Add new Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count); + } + + return Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + DateOpen = curModel.DateOpen, + MaxCount = curModel.MaxCount, + Adress = curModel.Adress, + ShopEngines = curModel.ShopEngines, + }); + } } } diff --git a/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs index 855a76f..75dbc6f 100644 --- a/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs +++ b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs @@ -13,6 +13,7 @@ namespace MotorPlantContracts.BindingModels public string ShopName { get; set; } public string Adress { get; set; } public DateTime DateOpen { get; set; } - public Dictionary ShopEngines { get; set; } = new(); + public int MaxCount { get; set; } + public Dictionary ShopEngines { get; set; } = new(); } } diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs index 919d97f..ce4f7b0 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -18,5 +18,6 @@ namespace MotorPlantContracts.BusinessLogicsContracts bool Update(ShopBindingModel? model); bool Delete(ShopBindingModel? model); bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); - } + bool MakeSell(IEngineModel model, int count); + } } diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs index 48c46db..0fb2755 100644 --- a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -1,6 +1,7 @@ using MotorPlantContracts.BindingModels; using MotorPlantContracts.SearchModels; using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; using System; using System.Collections.Generic; using System.Linq; @@ -17,5 +18,6 @@ namespace MotorPlantContracts.StoragesContracts ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model); - } + bool SellEngines(IEngineModel model, int count); + } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs index 4cd1610..7e595f5 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs @@ -24,6 +24,10 @@ namespace MotorPlantContracts.ViewModels public DateTime DateOpen { get; set; } - public Dictionary ShopEngines { get; set; } = new(); + [DisplayName("Вмещаемость")] + + public int MaxCount { get; set; } + + public Dictionary ShopEngines { get; set; } = new(); } } diff --git a/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs index 7552320..fef931e 100644 --- a/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs +++ b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs @@ -11,5 +11,6 @@ namespace MotorPlantDataModels.Models string ShopName { get; } string Adress { get; } DateTime DateOpen { get; } - } + int MaxCount { get; } + } } diff --git a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs index 8d52eb1..2d2bd6b 100644 --- a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs +++ b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs @@ -13,13 +13,17 @@ namespace MotorPlantFileImplement private readonly string EngineFileName = "Engine.xml"; - public List Components { get; private set; } + private readonly string ShopFileName = "Shop.xml"; + + public List Components { get; private set; } public List Orders { get; private set; } public List Engines { get; private set; } - public static DataFileSingleton GetInstance() + public List Shops { get; private set; } + + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -33,14 +37,17 @@ namespace MotorPlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); - private DataFileSingleton() + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Engines = LoadData(EngineFileName, "Engine", x => Engine.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; - } + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; + } - private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs new file mode 100644 index 0000000..aefb9ca --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -0,0 +1,121 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using MotorPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton _source; + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return _source.Shops.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + return _source.Shops.Where(x => x.ShopName.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); + + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + return _source.Shops.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.ShopName == model.Name) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + _source.SaveShops(); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + var component = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + _source.SaveShops(); + return component.GetViewModel; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + public bool CheckAvailability(int engineId, int count) + { + int store = _source.Shops.Select(x => x.ShopEngines.Select(y => (y.Value.Item1.Id == engineId ? y.Value.Item2 : 0)).Sum()).Sum(); + return store >= count; + } + public bool SellEngines(IEngineModel model, int count) + { + var dres = _source.Engines.FirstOrDefault(x => x.Id == model.Id); + + if (dres == null || !CheckAvailability(model.Id, count)) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var engines = shop.ShopEngines; + foreach (var engine in engines.Where(x => x.Value.Item1.Id == dres.Id)) + { + var selling = Math.Min(engine.Value.Item2, count); + engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); + + count -= selling; + + if (count <= 0) + { + break; + } + } + shop.Update(new ShopBindingModel + { + Id = model.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + MaxCount = shop.MaxCount, + DateOpen = shop.DateOpen, + ShopEngines = engines + }); + } + _source.SaveShops(); + return true; + } + } +} diff --git a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs new file mode 100644 index 0000000..98d151d --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs @@ -0,0 +1,102 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace MotorPlantFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Adress { get; private set; } + public DateTime DateOpen { get; private set; } + public int MaxCount { get; private set; } + public Dictionary Engines { get; private set; } = new(); + private Dictionary? _shopEngines = null; + + public Dictionary ShopEngines + { + get + { + if (_shopEngines == null) + { + var source = DataFileSingleton.GetInstance(); + _shopEngines = Engines.ToDictionary(x => x.Key, y => ((source.Engines.FirstOrDefault(z => z.Id == y.Key) as IEngineModel)!, y.Value)); + } + return _shopEngines; + } + } + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Shop() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Adress = element.Element("Adress")!.Value, + MaxCount = Convert.ToInt32(element.Element("MaxCount")!.Value), + DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value), + Engines = element.Element("ShopEngines")!.Elements("ShopEngine").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + if (model.ShopEngines.Count > 0) + { + Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopEngines = null; + } + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + + public XElement GetXElement => new XElement("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Adress", Adress), + new XElement("DateOpen", DateOpen), + new XElement("MaxCount", MaxCount), + new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); + } +} diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs index 6ba0064..2d61dae 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -2,6 +2,7 @@ using MotorPlantContracts.SearchModels; using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; using MotorPlantListImplement.Models; using System; using System.Collections.Generic; @@ -103,5 +104,13 @@ namespace MotorPlantListImplement.Implements } return null; } - } + public bool CheckAvailability(int engineId, int count) + { + return true; + } + public bool SellEngines(IEngineModel model, int count) + { + return true; + } + } } diff --git a/MotorPlant/MotorPlantListImplement/Models/Shop.cs b/MotorPlant/MotorPlantListImplement/Models/Shop.cs index ef03e2e..05ac9bd 100644 --- a/MotorPlant/MotorPlantListImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantListImplement/Models/Shop.cs @@ -15,7 +15,8 @@ namespace MotorPlantListImplement.Models public string ShopName { get; private set; } public string Adress { get; private set; } public DateTime DateOpen { get; private set; } - public Dictionary ShopEngines { get; private set; } = new(); + public int MaxCount { get; private set; } + public Dictionary ShopEngines { get; private set; } = new(); public static Shop? Create(ShopBindingModel model) { if (model == null) @@ -28,6 +29,7 @@ namespace MotorPlantListImplement.Models ShopName = model.ShopName, Adress = model.Adress, DateOpen = model.DateOpen, + MaxCount = model.MaxCount, ShopEngines = new() }; } @@ -40,6 +42,7 @@ namespace MotorPlantListImplement.Models ShopName = model.ShopName; Adress = model.Adress; DateOpen = model.DateOpen; + MaxCount = model.MaxCount; ShopEngines = model.ShopEngines; } public ShopViewModel GetViewModel => new() @@ -48,6 +51,7 @@ namespace MotorPlantListImplement.Models ShopName = ShopName, Adress = Adress, DateOpen = DateOpen, + MaxCount = MaxCount, ShopEngines = ShopEngines }; } diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index 33f0712..43ec273 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,205 +1,214 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + 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() - { - toolStrip1 = new ToolStrip(); - toolStripDropDownButton1 = new ToolStripDropDownButton(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - ДвигателиToolStripMenuItem = new ToolStripMenuItem(); - ShopsToolStripMenuItem = new ToolStripMenuItem(); - поставкиToolStripMenuItem = new ToolStripMenuItem(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - dataGridView = new DataGridView(); - toolStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // toolStrip1 - // - toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); - toolStrip1.Location = new Point(0, 0); - toolStrip1.Name = "toolStrip1"; - toolStrip1.Size = new Size(985, 25); - toolStrip1.TabIndex = 0; - toolStrip1.Text = "toolStrip1"; - // - // toolStripDropDownButton1 - // - toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, ShopsToolStripMenuItem, поставкиToolStripMenuItem }); - toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; - toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new Size(88, 22); - toolStripDropDownButton1.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; - // - // ShopsToolStripMenuItem - // - ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; - ShopsToolStripMenuItem.Size = new Size(180, 22); - ShopsToolStripMenuItem.Text = "Магазины"; - ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; - // - // поставкиToolStripMenuItem - // - поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; - поставкиToolStripMenuItem.Size = new Size(180, 22); - поставкиToolStripMenuItem.Text = "Поставки"; - поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; - // - // buttonCreateOrder - // - buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonCreateOrder.BackColor = SystemColors.ControlLight; - buttonCreateOrder.Location = new Point(797, 146); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(178, 30); - buttonCreateOrder.TabIndex = 1; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = false; - buttonCreateOrder.Click += buttonCreateOrder_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; - buttonTakeOrderInWork.Location = new Point(797, 194); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(178, 30); - buttonTakeOrderInWork.TabIndex = 2; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = false; - buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonOrderReady.BackColor = SystemColors.ControlLight; - buttonOrderReady.Location = new Point(797, 242); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(178, 30); - buttonOrderReady.TabIndex = 3; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = false; - buttonOrderReady.Click += buttonOrderReady_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonIssuedOrder.BackColor = SystemColors.ControlLight; - buttonIssuedOrder.Location = new Point(797, 287); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(178, 30); - buttonIssuedOrder.TabIndex = 4; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = false; - buttonIssuedOrder.Click += buttonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonRef.BackColor = SystemColors.ControlLight; - buttonRef.Location = new Point(797, 100); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(178, 30); - buttonRef.TabIndex = 5; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = false; - buttonRef.Click += buttonRef_Click; - // - // dataGridView - // - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(11, 28); - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(780, 441); - dataGridView.TabIndex = 6; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(985, 467); - Controls.Add(dataGridView); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(toolStrip1); - Name = "FormMain"; - Text = "Моторный завод"; - Load += FormMain_Load; - toolStrip1.ResumeLayout(false); - toolStrip1.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() + { + toolStrip1 = new ToolStrip(); + toolStripDropDownButton1 = new ToolStripDropDownButton(); + КомпонентыToolStripMenuItem = new ToolStripMenuItem(); + ДвигателиToolStripMenuItem = new ToolStripMenuItem(); + ShopsToolStripMenuItem = new ToolStripMenuItem(); + поставкиToolStripMenuItem = new ToolStripMenuItem(); + buttonCreateOrder = new Button(); + buttonTakeOrderInWork = new Button(); + buttonOrderReady = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + dataGridView = new DataGridView(); + продажаToolStripMenuItem = new ToolStripMenuItem(); + toolStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // toolStrip1 + // + toolStrip1.ImageScalingSize = new Size(20, 20); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); + toolStrip1.Location = new Point(0, 0); + toolStrip1.Name = "toolStrip1"; + toolStrip1.Size = new Size(985, 25); + toolStrip1.TabIndex = 0; + toolStrip1.Text = "toolStrip1"; + // + // toolStripDropDownButton1 + // + toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, ShopsToolStripMenuItem, поставкиToolStripMenuItem, продажаToolStripMenuItem }); + toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; + toolStripDropDownButton1.Name = "toolStripDropDownButton1"; + toolStripDropDownButton1.Size = new Size(88, 22); + toolStripDropDownButton1.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; + // + // ShopsToolStripMenuItem + // + ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; + ShopsToolStripMenuItem.Size = new Size(180, 22); + ShopsToolStripMenuItem.Text = "Магазины"; + ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + // + // поставкиToolStripMenuItem + // + поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; + поставкиToolStripMenuItem.Size = new Size(180, 22); + поставкиToolStripMenuItem.Text = "Поставки"; + поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; + // + // buttonCreateOrder + // + buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonCreateOrder.BackColor = SystemColors.ControlLight; + buttonCreateOrder.Location = new Point(797, 146); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(178, 30); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = false; + buttonCreateOrder.Click += buttonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; + buttonTakeOrderInWork.Location = new Point(797, 194); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(178, 30); + buttonTakeOrderInWork.TabIndex = 2; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = false; + buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonOrderReady.BackColor = SystemColors.ControlLight; + buttonOrderReady.Location = new Point(797, 242); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(178, 30); + buttonOrderReady.TabIndex = 3; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = false; + buttonOrderReady.Click += buttonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonIssuedOrder.BackColor = SystemColors.ControlLight; + buttonIssuedOrder.Location = new Point(797, 287); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(178, 30); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = false; + buttonIssuedOrder.Click += buttonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.BackColor = SystemColors.ControlLight; + buttonRef.Location = new Point(797, 100); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(178, 30); + buttonRef.TabIndex = 5; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = false; + buttonRef.Click += buttonRef_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(11, 28); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 24; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(780, 441); + dataGridView.TabIndex = 6; + // + // продажаToolStripMenuItem + // + продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; + продажаToolStripMenuItem.Size = new Size(180, 22); + продажаToolStripMenuItem.Text = "Продажа"; + продажаToolStripMenuItem.Click += SellToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(985, 467); + Controls.Add(dataGridView); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(toolStrip1); + Name = "FormMain"; + Text = "Моторный завод"; + Load += FormMain_Load; + toolStrip1.ResumeLayout(false); + toolStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private ToolStrip toolStrip1; - private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button buttonOrderReady; - private Button buttonIssuedOrder; - private Button buttonRef; - private DataGridView dataGridView; - private ToolStripDropDownButton toolStripDropDownButton1; - private ToolStripMenuItem КомпонентыToolStripMenuItem; - private ToolStripMenuItem ДвигателиToolStripMenuItem; - private ToolStripMenuItem ShopsToolStripMenuItem; - private ToolStripMenuItem поставкиToolStripMenuItem; - } + private ToolStrip toolStrip1; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonIssuedOrder; + private Button buttonRef; + private DataGridView dataGridView; + private ToolStripDropDownButton toolStripDropDownButton1; + private ToolStripMenuItem КомпонентыToolStripMenuItem; + private ToolStripMenuItem ДвигателиToolStripMenuItem; + private ToolStripMenuItem ShopsToolStripMenuItem; + private ToolStripMenuItem поставкиToolStripMenuItem; + private ToolStripMenuItem продажаToolStripMenuItem; + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index 3172e11..e3468ed 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -5,163 +5,171 @@ using MotorPlantView; namespace MotorPlantView.Forms { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + public FormMain(ILogger logger, IOrderLogic orderLogic) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + } + } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); - if (service is FormEngines form) - { - form.ShowDialog(); - } - } - private void buttonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - 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) - { - 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("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormEngines form) + { + form.ShowDialog(); + } + } + private void buttonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + 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); + var engineId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["EngineId"].Value); + var count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value); + _logger.LogInformation("Order №{id}. Change status on 'Ready'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id, EngineId = engineId, Count = count }); + 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) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Order №{id}. Status change on 'Given'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Order №{id} given", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Change status on 'Give' error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); - if (service is FormShops form) - { - form.ShowDialog(); - } - } + if (service is FormShops form) + { + form.ShowDialog(); + } + } - private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); - if (service is FormSupply form) - { - form.ShowDialog(); - } - } - } + if (service is FormSupply form) + { + form.ShowDialog(); + } + } + + private void SellToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (service is FormSell form) + { + form.ShowDialog(); + } + } + } } diff --git a/MotorPlant/MotorPlantView/FormSell.Designer.cs b/MotorPlant/MotorPlantView/FormSell.Designer.cs new file mode 100644 index 0000000..3696490 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.Designer.cs @@ -0,0 +1,122 @@ +namespace MotorPlantView +{ + partial class FormSell + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + comboBoxEngine = new ComboBox(); + textBoxCount = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + // + // comboBoxEngine + // + comboBoxEngine.FormattingEnabled = true; + comboBoxEngine.Location = new Point(110, 22); + comboBoxEngine.Margin = new Padding(3, 2, 3, 2); + comboBoxEngine.Name = "comboBoxEngine"; + comboBoxEngine.Size = new Size(133, 23); + comboBoxEngine.TabIndex = 0; + // + // textBoxCount + // + textBoxCount.Location = new Point(110, 71); + textBoxCount.Margin = new Padding(3, 2, 3, 2); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(133, 23); + textBoxCount.TabIndex = 1; + // + // buttonSave + // + buttonSave.Location = new Point(39, 129); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 2; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(160, 129); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 3; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(24, 25); + label1.Name = "label1"; + label1.Size = new Size(50, 15); + label1.TabIndex = 4; + label1.Text = "Движки"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(24, 74); + label2.Name = "label2"; + label2.Size = new Size(72, 15); + label2.TabIndex = 5; + label2.Text = "Количество"; + // + // FormSell + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(268, 176); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxCount); + Controls.Add(comboBoxEngine); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSell"; + Text = "Продажа"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxEngine; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSell.cs b/MotorPlant/MotorPlantView/FormSell.cs new file mode 100644 index 0000000..09d47ad --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MotorPlantDataModels.Models; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.ViewModels; + +namespace MotorPlantView +{ + public partial class FormSell : Form + { + private readonly List? _engineList; + IShopLogic _shopLogic; + IEngineLogic _engineLogic; + public FormSell(IEngineLogic engineLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _engineLogic = engineLogic; + _engineList = engineLogic.ReadList(null); + if (_engineList != null) + { + comboBoxEngine.DisplayMember = "EngineName"; + comboBoxEngine.ValueMember = "Id"; + comboBoxEngine.DataSource = _engineList; + comboBoxEngine.SelectedItem = null; + } + } + public int EngineId + { + get + { + return Convert.ToInt32(comboBoxEngine.SelectedValue); + } + set + { + comboBoxEngine.SelectedValue = value; + } + } + + public IEngineModel? EngineModel + { + get + { + if (_engineList == null) + { + return null; + } + foreach (var elem in _engineList) + { + if (elem.Id == EngineId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set + { textBoxCount.Text = value.ToString(); } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxEngine.SelectedValue == null) + { + MessageBox.Show("Выберите двигатель", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(textBoxCount.Text); + + bool res = _shopLogic.MakeSell( + _engineLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxEngine.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при продаже."); + } + + MessageBox.Show("Продажа прошла успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка продажи"); + return; + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormSell.resx b/MotorPlant/MotorPlantView/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShop.Designer.cs b/MotorPlant/MotorPlantView/FormShop.Designer.cs index 9e574fc..a529389 100644 --- a/MotorPlant/MotorPlantView/FormShop.Designer.cs +++ b/MotorPlant/MotorPlantView/FormShop.Designer.cs @@ -1,193 +1,226 @@ namespace MotorPlantView { - partial class FormShop - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + 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() - { - dateTimePicker = new DateTimePicker(); - textBoxName = new TextBox(); - textBoxAdress = new TextBox(); - dataGridView = new DataGridView(); - IdColumn = new DataGridViewTextBoxColumn(); - Title = new DataGridViewTextBoxColumn(); - Cost = new DataGridViewTextBoxColumn(); - Count = new DataGridViewTextBoxColumn(); - buttonSave = new Button(); - buttonCancel = new Button(); - label1 = new Label(); - label2 = new Label(); - label3 = new Label(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // dateTimePicker - // - dateTimePicker.Location = new Point(714, 34); - dateTimePicker.Name = "dateTimePicker"; - dateTimePicker.Size = new Size(250, 27); - dateTimePicker.TabIndex = 0; - // - // textBoxName - // - textBoxName.Location = new Point(714, 85); - textBoxName.Name = "textBoxName"; - textBoxName.Size = new Size(250, 27); - textBoxName.TabIndex = 1; - // - // textBoxAdress - // - textBoxAdress.Location = new Point(714, 139); - textBoxAdress.Name = "textBoxAdress"; - textBoxAdress.Size = new Size(250, 27); - textBoxAdress.TabIndex = 2; - // - // dataGridView - // - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Columns.AddRange(new DataGridViewColumn[] { IdColumn, Title, Cost, Count }); - dataGridView.Location = new Point(10, 32); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(554, 380); - dataGridView.TabIndex = 3; - // - // IdColumn - // - IdColumn.HeaderText = "Номер платья"; - IdColumn.MinimumWidth = 6; - IdColumn.Name = "IdColumn"; - IdColumn.Visible = false; - IdColumn.Width = 125; - // - // Title - // - Title.HeaderText = "Название"; - Title.MinimumWidth = 6; - Title.Name = "Title"; - Title.Width = 125; - // - // Cost - // - Cost.HeaderText = "Цена"; - Cost.MinimumWidth = 6; - Cost.Name = "Cost"; - Cost.Width = 125; - // - // Count - // - Count.HeaderText = "Количество"; - Count.MinimumWidth = 6; - Count.Name = "Count"; - Count.Width = 125; - // - // buttonSave - // - buttonSave.Location = new Point(714, 219); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(94, 29); - buttonSave.TabIndex = 4; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; - // - // buttonCancel - // - buttonCancel.Location = new Point(870, 219); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(94, 29); - buttonCancel.TabIndex = 5; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; - // - // label1 - // - label1.AutoSize = true; - label1.Location = new Point(592, 39); - label1.Name = "label1"; - label1.Size = new Size(110, 20); - label1.TabIndex = 6; - label1.Text = "Дата создания"; - // - // label2 - // - label2.AutoSize = true; - label2.Location = new Point(592, 88); - label2.Name = "label2"; - label2.Size = new Size(77, 20); - label2.TabIndex = 7; - label2.Text = "Название"; - // - // label3 - // - label3.AutoSize = true; - label3.Location = new Point(592, 142); - label3.Name = "label3"; - label3.Size = new Size(51, 20); - label3.TabIndex = 8; - label3.Text = "Адрес"; - // - // ShopForm - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(976, 450); - Controls.Add(label3); - Controls.Add(label2); - Controls.Add(label1); - Controls.Add(buttonCancel); - Controls.Add(buttonSave); - Controls.Add(dataGridView); - Controls.Add(textBoxAdress); - Controls.Add(textBoxName); - Controls.Add(dateTimePicker); - Name = "ShopForm"; - Text = "Форма магазина"; - Load += ShopForm_Load; - ((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() + { + dateTimePicker = new DateTimePicker(); + textBoxName = new TextBox(); + textBoxAdress = new TextBox(); + dataGridView = new DataGridView(); + IdColumn = new DataGridViewTextBoxColumn(); + Title = new DataGridViewTextBoxColumn(); + Cost = new DataGridViewTextBoxColumn(); + Count = new DataGridViewTextBoxColumn(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + numeric = new NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numeric).BeginInit(); + SuspendLayout(); + // + // dateTimePicker + // + dateTimePicker.Location = new Point(625, 26); + dateTimePicker.Margin = new Padding(3, 2, 3, 2); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(219, 23); + dateTimePicker.TabIndex = 0; + // + // textBoxName + // + textBoxName.Location = new Point(625, 64); + textBoxName.Margin = new Padding(3, 2, 3, 2); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(219, 23); + textBoxName.TabIndex = 1; + // + // textBoxAdress + // + textBoxAdress.Location = new Point(625, 104); + textBoxAdress.Margin = new Padding(3, 2, 3, 2); + textBoxAdress.Name = "textBoxAdress"; + textBoxAdress.Size = new Size(219, 23); + textBoxAdress.TabIndex = 2; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { IdColumn, Title, Cost, Count }); + dataGridView.Location = new Point(9, 24); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(485, 285); + dataGridView.TabIndex = 3; + // + // IdColumn + // + IdColumn.HeaderText = "Номер платья"; + IdColumn.MinimumWidth = 6; + IdColumn.Name = "IdColumn"; + IdColumn.Visible = false; + IdColumn.Width = 125; + // + // Title + // + Title.HeaderText = "Название"; + Title.MinimumWidth = 6; + Title.Name = "Title"; + Title.Width = 125; + // + // Cost + // + Cost.HeaderText = "Цена"; + Cost.MinimumWidth = 6; + Cost.Name = "Cost"; + Cost.Width = 125; + // + // Count + // + Count.HeaderText = "Количество"; + Count.MinimumWidth = 6; + Count.Name = "Count"; + Count.Width = 125; + // + // buttonSave + // + buttonSave.Location = new Point(625, 179); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 4; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(761, 179); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(518, 29); + label1.Name = "label1"; + label1.Size = new Size(85, 15); + label1.TabIndex = 6; + label1.Text = "Дата создания"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(518, 66); + label2.Name = "label2"; + label2.Size = new Size(59, 15); + label2.TabIndex = 7; + label2.Text = "Название"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(518, 106); + label3.Name = "label3"; + label3.Size = new Size(40, 15); + label3.TabIndex = 8; + label3.Text = "Адрес"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(518, 144); + label4.Name = "label4"; + label4.Size = new Size(80, 15); + label4.TabIndex = 9; + label4.Text = "Вместимость"; + label4.TextAlign = ContentAlignment.TopCenter; + // + // numeric + // + numeric.Location = new Point(625, 142); + numeric.Margin = new Padding(3, 2, 3, 2); + numeric.Name = "numeric"; + numeric.Size = new Size(131, 23); + numeric.TabIndex = 10; + // + // FormShop + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(854, 338); + Controls.Add(numeric); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(dataGridView); + Controls.Add(textBoxAdress); + Controls.Add(textBoxName); + Controls.Add(dateTimePicker); + Margin = new Padding(3, 2, 3, 2); + Name = "FormShop"; + Text = "Форма магазина"; + Load += ShopForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numeric).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private DateTimePicker dateTimePicker; - private TextBox textBoxName; - private TextBox textBoxAdress; - private DataGridView dataGridView; - private Button buttonSave; - private Button buttonCancel; - private Label label1; - private Label label2; - private Label label3; - private DataGridViewTextBoxColumn IdColumn; - private DataGridViewTextBoxColumn Title; - private DataGridViewTextBoxColumn Cost; - private DataGridViewTextBoxColumn Count; - } + private DateTimePicker dateTimePicker; + private TextBox textBoxName; + private TextBox textBoxAdress; + private DataGridView dataGridView; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + private Label label3; + private DataGridViewTextBoxColumn IdColumn; + private DataGridViewTextBoxColumn Title; + private DataGridViewTextBoxColumn Cost; + private DataGridViewTextBoxColumn Count; + private Label label4; + private NumericUpDown numeric; + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShop.cs b/MotorPlant/MotorPlantView/FormShop.cs index e1c45bb..497ffe8 100644 --- a/MotorPlant/MotorPlantView/FormShop.cs +++ b/MotorPlant/MotorPlantView/FormShop.cs @@ -15,108 +15,109 @@ using System.Windows.Forms; namespace MotorPlantView { - public partial class FormShop : Form - { - private readonly ILogger _logger; - private readonly IShopLogic _logic; - public int? _id; - private Dictionary _engine; - public FormShop(ILogger logger, IShopLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public int? _id; + private Dictionary _engines; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } - private void ShopForm_Load(object sender, EventArgs e) - { - if (_id.HasValue) - { - _logger.LogInformation("Shop load"); - try - { - var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); - if (shop != null) - { - textBoxName.Text = shop.ShopName; - textBoxAdress.Text = shop.Adress; - dateTimePicker.Text = shop.DateOpen.ToString(); - _engine = shop.ShopEngines; - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Load shop error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } + private void ShopForm_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Shop load"); + try + { + var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); + if (shop != null) + { + textBoxName.Text = shop.ShopName; + textBoxAdress.Text = shop.Adress; + dateTimePicker.Text = shop.DateOpen.ToString(); + numeric.Value = shop.MaxCount; + _engines = shop.ShopEngines ?? new Dictionary(); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } - private void LoadData() - { - _logger.LogInformation("Load engines"); - try - { - if (_engine != null) - { - foreach (var engine in _engine) - { - dataGridView.Rows.Add(new object[] { engine.Key, engine.Value.Item1.EngineName, engine.Value.Item1.Price, engine.Value.Item2 }); - } - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Load engines into shop error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - private void buttonSave_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxName.Text)) - { - MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (string.IsNullOrEmpty(textBoxAdress.Text)) - { - MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - _logger.LogInformation("Save shop"); - try - { - var model = new ShopBindingModel - { - Id = _id ?? 0, - ShopName = textBoxName.Text, - Adress = textBoxAdress.Text, - DateOpen = dateTimePicker.Value.Date, - ShopEngines = _engine - }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Save shop error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void LoadData() + { + _logger.LogInformation("Load engines"); + try + { + if (_engines != null) + { + foreach (var engine in _engines) + { + dataGridView.Rows.Add(new object[] { engine.Key, engine.Value.Item1.EngineName, engine.Value.Item1.Price, engine.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Load engines into shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Save shop"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + DateOpen = dateTimePicker.Value.Date, + MaxCount = Convert.ToInt32(numeric.Value) + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Save shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void buttonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } - } + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } } diff --git a/MotorPlant/MotorPlantView/FormShop.resx b/MotorPlant/MotorPlantView/FormShop.resx index 1af7de1..af32865 100644 --- a/MotorPlant/MotorPlantView/FormShop.resx +++ b/MotorPlant/MotorPlantView/FormShop.resx @@ -1,17 +1,17 @@  - diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index e7c5acf..088c50c 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -55,6 +55,7 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + } } } \ No newline at end of file From dcef17c190b741fe7f5e4b88a7328cc24f59853a Mon Sep 17 00:00:00 2001 From: Salikh Date: Thu, 11 Apr 2024 17:04:57 +0400 Subject: [PATCH 09/13] first commit --- .../Implements/ShopStorage.cs | 144 ++++++++++++++++++ ...40411122818_InitHardMigration.Designer.cs} | 81 +++++++++- ...cs => 20240411122818_InitHardMigration.cs} | 61 +++++++- .../MotorPlantDatabaseModelSnapshot.cs | 77 ++++++++++ .../Models/Order.cs | 2 - .../Models/Shop.cs | 105 +++++++++++++ .../Models/ShopEngine.cs | 22 +++ .../MotorPlantDatabase.cs | 6 +- .../MotorPlantDatabaseImplement.csproj | 4 - MotorPlant/MotorPlantView/FormCreateOrder.cs | 5 +- MotorPlant/MotorPlantView/FormMain.cs | 2 +- 11 files changed, 495 insertions(+), 14 deletions(-) create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240403225731_InitMigration.Designer.cs => 20240411122818_InitHardMigration.Designer.cs} (68%) rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240403225731_InitMigration.cs => 20240411122818_InitHardMigration.cs} (66%) create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..5772557 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,144 @@ +using Microsoft.EntityFrameworkCore; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDatabaseImplement.Models; +using MotorPlantDataModels.Models; + +namespace MotorPlantDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new MotorPlantDatabase(); + return context.Shops + .Include(x => x.Engines) + .ThenInclude(x => x.Engine) + .Select(x => x.GetViewModel) + .Where(x => x.ShopName.Contains(model.Name ?? string.Empty)) + .ToList(); + } + + public List GetFullList() + { + using var context = new MotorPlantDatabase(); + return context.Shops + .Include(x => x.Engines) + .ThenInclude(x => x.Engine) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + try + { + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + if (context.Shops.Any(x => x.ShopName == newShop.ShopName)) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + catch + { + throw; + } + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + try + { + if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + shop.Update(model); + shop.UpdateDresses(context, model); + context.SaveChanges(); + return shop.GetViewModel; + } + catch + { + throw; + } + } + public bool SellEngines(IEngineModel model, int count) + { + if (model == null) + return false; + using var context = new MotorPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + List lst = new List(); + foreach (var el in context.ShopEngines.Where(x => x.EngineId == model.Id)) + { + int dif = count; + if (el.Count < dif) + dif = el.Count; + el.Count -= dif; + count -= dif; + if (el.Count == 0) + { + lst.Add(el); + } + if (count == 0) + break; + } + if (count > 0) + { + transaction.Rollback(); + return false; + } + foreach (var el in lst) + { + context.ShopEngines.Remove(el); + } + context.SaveChanges(); + transaction.Commit(); + return true; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.Designer.cs similarity index 68% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.Designer.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.Designer.cs index 575ec39..8b2c5f9 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.Designer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.Designer.cs @@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { [DbContext(typeof(MotorPlantDatabase))] - [Migration("20240403225731_InitMigration")] - partial class InitMigration + [Migration("20240411122818_InitHardMigration")] + partial class InitHardMigration { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -124,6 +124,59 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateOpen") + .HasColumnType("timestamp without time zone"); + + b.Property("MaxCount") + .HasColumnType("integer"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("ShopId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopEngines"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => { b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") @@ -154,6 +207,25 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Engine"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany() + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Engines") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Engine"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => { b.Navigation("EngineComponents"); @@ -165,6 +237,11 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Engines"); + }); #pragma warning restore 612, 618 } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.cs similarity index 66% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.cs index 53bde97..46dc8e1 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240403225731_InitMigration.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { /// - public partial class InitMigration : Migration + public partial class InitHardMigration : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -40,6 +40,22 @@ namespace MotorPlantDatabaseImplement.Migrations table.PrimaryKey("PK_Engines", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ShopName = table.Column(type: "text", nullable: false), + Adress = table.Column(type: "text", nullable: false), + DateOpen = table.Column(type: "timestamp without time zone", nullable: false), + MaxCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + migrationBuilder.CreateTable( name: "EngineComponents", columns: table => new @@ -91,6 +107,33 @@ namespace MotorPlantDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "ShopEngines", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + EngineId = table.Column(type: "integer", nullable: false), + ShopId = table.Column(type: "integer", nullable: false), + Count = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopEngines", x => x.Id); + table.ForeignKey( + name: "FK_ShopEngines_Engines_EngineId", + column: x => x.EngineId, + principalTable: "Engines", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopEngines_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateIndex( name: "IX_EngineComponents_ComponentId", table: "EngineComponents", @@ -105,6 +148,16 @@ namespace MotorPlantDatabaseImplement.Migrations name: "IX_Orders_EngineId", table: "Orders", column: "EngineId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopEngines_EngineId", + table: "ShopEngines", + column: "EngineId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopEngines_ShopId", + table: "ShopEngines", + column: "ShopId"); } /// @@ -116,11 +169,17 @@ namespace MotorPlantDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Orders"); + migrationBuilder.DropTable( + name: "ShopEngines"); + migrationBuilder.DropTable( name: "Components"); migrationBuilder.DropTable( name: "Engines"); + + migrationBuilder.DropTable( + name: "Shops"); } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs index 8e0807e..51fdedd 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs @@ -121,6 +121,59 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateOpen") + .HasColumnType("timestamp without time zone"); + + b.Property("MaxCount") + .HasColumnType("integer"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("ShopId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopEngines"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => { b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") @@ -151,6 +204,25 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Engine"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany() + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Engines") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Engine"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => { b.Navigation("EngineComponents"); @@ -162,6 +234,11 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Engines"); + }); #pragma warning restore 612, 618 } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 00cb15b..91450c6 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -43,7 +43,6 @@ namespace MotorPlantDatabaseImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement }; } @@ -66,7 +65,6 @@ namespace MotorPlantDatabaseImplement.Models Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - EngineName = Engine.EngineName }; } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..1aa014d --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs @@ -0,0 +1,105 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + [Required] + public string ShopName { get; private set; } + [Required] + public string Adress { get; private set; } + [Required] + public DateTime DateOpen { get; private set; } + [Required] + public int MaxCount { get; private set; } + private Dictionary? _shopEngines = null; + [NotMapped] + public Dictionary? ShopEngines + { + get + { + if (_shopEngines == null) + { + _shopEngines = Engines.ToDictionary(x => x.EngineId, x => (x.Engine as IEngineModel, x.Count)); + } + return _shopEngines; + } + } + [ForeignKey("ShopId")] + public virtual List Engines { get; set; } = new(); + public static Shop? Create(MotorPlantDatabase context, ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + Engines = model.ShopEngines.Select(x => new ShopEngine + { + Engine = context.Engines.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + return; + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + + public void UpdateDresses(MotorPlantDatabase context, ShopBindingModel model) + { + var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); + if (shopEngines != null && shopEngines.Count > 0) + { + context.ShopEngines.RemoveRange(shopEngines.Where(rec => !model.ShopEngines.ContainsKey(rec.EngineId))); + context.SaveChanges(); + foreach (var uEngine in shopEngines) + { + uEngine.Count = model.ShopEngines[uEngine.EngineId].Item2; + model.ShopEngines.Remove(uEngine.EngineId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var pc in model.ShopEngines) + { + context.ShopEngines.Add(new ShopEngine + { + Shop = shop, + Engine = context.Engines.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _shopEngines = null; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs new file mode 100644 index 0000000..c6ed0c0 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class ShopEngine + { + public int Id { get; set; } + [Required] + public int EngineId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + public virtual Shop Shop { get; set; } = new(); + public virtual Engine Engine { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs index 26ecf49..73a1df5 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs @@ -9,7 +9,7 @@ namespace MotorPlantDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_db;Username=postgres;Password=admin"); + optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlantHard_db;Username=postgres;Password=admin"); } base.OnConfiguring(optionsBuilder); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); @@ -19,5 +19,7 @@ namespace MotorPlantDatabaseImplement public virtual DbSet Engines { get; set; } public virtual DbSet EngineComponents { get; set; } public virtual DbSet Orders { get; set; } - } + public virtual DbSet Shops { get; set; } + public virtual DbSet ShopEngines { get; set; } + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj index 6fa33d6..fa3b43b 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj @@ -21,8 +21,4 @@ - - - - diff --git a/MotorPlant/MotorPlantView/FormCreateOrder.cs b/MotorPlant/MotorPlantView/FormCreateOrder.cs index d4fd6e3..63df012 100644 --- a/MotorPlant/MotorPlantView/FormCreateOrder.cs +++ b/MotorPlant/MotorPlantView/FormCreateOrder.cs @@ -84,7 +84,7 @@ namespace MotorPlantView.Forms var operationResult = _logicO.CreateOrder(new OrderBindingModel { EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue), - Count = Convert.ToInt32(textBoxCount.Text), + Count = Convert.ToInt32(textBoxCount.Text), Sum = Convert.ToDouble(textBoxSum.Text) }); if (!operationResult) @@ -97,7 +97,8 @@ namespace MotorPlantView.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка создания заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index e3468ed..01227b8 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -30,7 +30,7 @@ namespace MotorPlantView.Forms { dataGridView.DataSource = list; dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; } _logger.LogInformation("Загрузка заказов"); From 1cb89e24d726a3dce461a29a931a74412de9a57d Mon Sep 17 00:00:00 2001 From: Salikh Date: Thu, 11 Apr 2024 18:22:36 +0400 Subject: [PATCH 10/13] second commit --- .../Implements/OrderStorage.cs | 123 +++++++++--------- ...r.cs => 20240411140319_NewMig.Designer.cs} | 8 +- ...dMigration.cs => 20240411140319_NewMig.cs} | 2 +- .../MotorPlantDatabaseModelSnapshot.cs | 4 +- .../Models/Order.cs | 2 - 5 files changed, 69 insertions(+), 70 deletions(-) rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240411122818_InitHardMigration.Designer.cs => 20240411140319_NewMig.Designer.cs} (98%) rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240411122818_InitHardMigration.cs => 20240411140319_NewMig.cs} (99%) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs index 08c17f1..ae20ebb 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs @@ -13,8 +13,10 @@ namespace MotorPlantDatabaseImplement.Implements public List GetFullList() { using var context = new MotorPlantDatabase(); - return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList(); - } + return context.Orders + .Select(x => AccessEngineStorage(x.GetViewModel)) + .ToList(); + } public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue) @@ -22,67 +24,70 @@ namespace MotorPlantDatabaseImplement.Implements return new(); } using var context = new MotorPlantDatabase(); - return context.Orders - .Include(x => x.Engine) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); - } + return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); + } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - using var context = new MotorPlantDatabase(); - return context.Orders.Include(x => x.Engine) - .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - } + if (!model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); + } public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - using var context = new MotorPlantDatabase(); - context.Orders.Add(newOrder); - context.SaveChanges(); - return context.Orders - .Include(x => x.Engine) - .FirstOrDefault(x => x.Id == newOrder.Id) - ?.GetViewModel; - } + var newOrder = Order.Create(model); + if (newOrder == null) + { + return null; + } + using var context = new MotorPlantDatabase(); + context.Orders.Add(newOrder); + context.SaveChanges(); + return AccessEngineStorage(newOrder.GetViewModel); + } public OrderViewModel? Update(OrderBindingModel model) { - using var context = new MotorPlantDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return context.Orders - .Include(x => x.Engine) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - } - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new MotorPlantDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - var deletedElement = context.Orders - .Include(x => x.Engine) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - context.Orders.Remove(element); - context.SaveChanges(); - return deletedElement; - } - return null; - } - } + using var context = new MotorPlantDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == + model.Id); + if (order == null) + { + return null; + } + order.Update(model); + context.SaveChanges(); + return AccessEngineStorage(order.GetViewModel); + } + + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Orders.Remove(element); + context.SaveChanges(); + return AccessEngineStorage(element.GetViewModel); + } + return null; + } + + public static OrderViewModel AccessEngineStorage(OrderViewModel model) + { + if (model == null) + return null; + using var context = new MotorPlantDatabase(); + foreach (var Engine in context.Engines) + { + if (Engine.Id == model.EngineId) + { + model.EngineName = Engine.EngineName; + break; + } + } + return model; + } + } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.Designer.cs similarity index 98% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.Designer.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.Designer.cs index 8b2c5f9..1151db6 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.Designer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.Designer.cs @@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { [DbContext(typeof(MotorPlantDatabase))] - [Migration("20240411122818_InitHardMigration")] - partial class InitHardMigration + [Migration("20240411140319_NewMig")] + partial class NewMig { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -198,13 +198,11 @@ namespace MotorPlantDatabaseImplement.Migrations modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { - b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) .WithMany("Orders") .HasForeignKey("EngineId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - - b.Navigation("Engine"); }); modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs similarity index 99% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs index 46dc8e1..5a17410 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411122818_InitHardMigration.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { /// - public partial class InitHardMigration : Migration + public partial class NewMig : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs index 51fdedd..e59cde0 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs @@ -195,13 +195,11 @@ namespace MotorPlantDatabaseImplement.Migrations modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { - b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) .WithMany("Orders") .HasForeignKey("EngineId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - - b.Navigation("Engine"); }); modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 91450c6..7355218 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -27,8 +27,6 @@ namespace MotorPlantDatabaseImplement.Models public DateTime? DateImplement { get; private set; } - public virtual Engine Engine { get; set; } - public static Order? Create(OrderBindingModel? model) { if (model == null) From 6456ec0dbf39160e3f512bd26137a4ba6469b7bd Mon Sep 17 00:00:00 2001 From: Salikh Date: Fri, 3 May 2024 15:44:28 +0400 Subject: [PATCH 11/13] commit --- .../Implements/ShopStorage .cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs index aefb9ca..29ae922 100644 --- a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -74,16 +74,13 @@ namespace MotorPlantFileImplement.Implements } return null; } - public bool CheckAvailability(int engineId, int count) - { - int store = _source.Shops.Select(x => x.ShopEngines.Select(y => (y.Value.Item1.Id == engineId ? y.Value.Item2 : 0)).Sum()).Sum(); - return store >= count; - } + public bool SellEngines(IEngineModel model, int count) { - var dres = _source.Engines.FirstOrDefault(x => x.Id == model.Id); + var eng = _source.Engines.FirstOrDefault(x => x.Id == model.Id); + int store = _source.Shops.SelectMany(x => x.ShopEngines).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); - if (dres == null || !CheckAvailability(model.Id, count)) + if (eng == null || store < count) { return false; } @@ -92,7 +89,7 @@ namespace MotorPlantFileImplement.Implements { var shop = _source.Shops[i]; var engines = shop.ShopEngines; - foreach (var engine in engines.Where(x => x.Value.Item1.Id == dres.Id)) + foreach (var engine in engines.Where(x => x.Value.Item1.Id == eng.Id)) { var selling = Math.Min(engine.Value.Item2, count); engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); From 3bcb1fcdb0a488d43abf3ef1f81e54868dba5fb1 Mon Sep 17 00:00:00 2001 From: Salikh Date: Thu, 16 May 2024 21:30:31 +0400 Subject: [PATCH 12/13] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index ca1c7a3..7f76508 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,11 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# dll файлы +*.dll + +/MotorPlant/ImplementationExtensions + # Mono auto generated files mono_crash.* From c1c043c6c334f62ee8b35b0a102542bbe5391e99 Mon Sep 17 00:00:00 2001 From: Salikh Date: Fri, 17 May 2024 03:17:15 +0400 Subject: [PATCH 13/13] first commit --- .../BusinessLogic/OrderLogic.cs | 187 +++----- .../BusinessLogic/ReportLogic.cs | 96 ++-- .../BusinessLogic/ShopLogic.cs | 109 +++-- .../OfficePackage/AbstractSaveToExcel.cs | 93 +++- .../OfficePackage/AbstractSaveToPdf.cs | 33 +- .../OfficePackage/AbstractSaveToWord.cs | 60 ++- .../OfficePackage/HelperModels/ExcelInfo.cs | 2 +- .../OfficePackage/HelperModels/ExcelShop.cs | 11 + .../HelperModels/PdfGroupedOrdersInfo.cs | 13 + .../OfficePackage/HelperModels/PdfInfo.cs | 2 +- .../OfficePackage/HelperModels/WordInfo.cs | 2 +- .../HelperModels/WordRowParameters.cs | 14 + .../HelperModels/WordShopInfo.cs | 16 + .../OfficePackage/IDocument.cs | 14 + .../OfficePackage/Implements/SaveToExcel.cs | 4 +- .../OfficePackage/Implements/SaveToPdf.cs | 4 +- .../OfficePackage/Implements/SaveToWord .cs | 76 ++- .../BindingModels/SupplyBindingModel.cs | 16 + .../BusinessLogicsContracts/IReportLogic.cs | 9 +- .../BusinessLogicsContracts/IShopLogic.cs | 10 +- .../SearchModels/SupplySearchModel.cs | 14 + .../StoragesContracts/IShopStorage.cs | 5 +- .../ViewModels/ReportGroupOrdersViewModel.cs | 15 + .../ViewModels/ReportShopsViewModel.cs | 9 + .../Models/ISupplyModel.cs | 15 + .../Implements/OrderStorage.cs | 116 +++-- .../Implements/ShopStorage.cs | 166 ++++--- .../20240516204547_ThirdMigtation.Designer.cs | 246 ++++++++++ ...ig.cs => 20240516204547_ThirdMigtation.cs} | 2 +- .../Models/Order.cs | 10 +- .../Models/Shop.cs | 23 +- .../Implements/ShopStorage .cs | 105 +++-- .../MotorPlantFileImplement/Models/Shop.cs | 7 +- .../Implements/OrderStorage.cs | 2 +- .../Implements/ShopStorage.cs | 13 +- .../MotorPlantView/FormMain.Designer.cs | 98 +++- MotorPlant/MotorPlantView/FormMain.cs | 114 ++++- .../FormReportGroupedOrders.Designer.cs | 86 ++++ .../MotorPlantView/FormReportGroupedOrders.cs | 80 ++++ .../FormReportGroupedOrders.resx | 120 +++++ .../MotorPlantView/FormReportShop.Designer.cs | 116 +++++ MotorPlant/MotorPlantView/FormReportShop.cs | 78 ++++ MotorPlant/MotorPlantView/FormReportShop.resx | 120 +++++ MotorPlant/MotorPlantView/FormSell.cs | 67 ++- MotorPlant/MotorPlantView/FormSupply.cs | 45 +- MotorPlant/MotorPlantView/Program.cs | 9 + .../MotorPlantView/ReportGroupedOrders.rdlc | 441 ++++++++++++++++++ 47 files changed, 2356 insertions(+), 537 deletions(-) create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs create mode 100644 MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240411140319_NewMig.cs => 20240516204547_ThirdMigtation.cs} (99%) create mode 100644 MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormReportGroupedOrders.cs create mode 100644 MotorPlant/MotorPlantView/FormReportGroupedOrders.resx create mode 100644 MotorPlant/MotorPlantView/FormReportShop.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormReportShop.cs create mode 100644 MotorPlant/MotorPlantView/FormReportShop.resx create mode 100644 MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index c3322c1..3277e2f 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -14,15 +14,12 @@ namespace MotorPlantBusinessLogic.BusinessLogics private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; private readonly IShopStorage _shopStorage; - private readonly IShopLogic _shopLogic; - private readonly IEngineStorage _engineStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IEngineStorage engineStorage) + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; _shopStorage = shopStorage; - _shopLogic = shopLogic; - _engineStorage = engineStorage; } public List? ReadList(OrderSearchModel? model) @@ -38,22 +35,31 @@ namespace MotorPlantBusinessLogic.BusinessLogics return list; } - private void CheckModel(OrderBindingModel model) + private void CheckModel(OrderBindingModel model, bool WithParams = true) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (model.Count <= 0) - { - throw new ArgumentNullException("Количество заказов должно быть больше нуля"); - } - if (model.Sum <= 0) - { - throw new ArgumentNullException("Цена заказа должна быть больше нуля"); - } - _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}", model.Id, model.Sum); - } + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!WithParams) + { + return; + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество движков в заказе не может быть меньше 1", nameof(model.Count)); + } + if (model.Sum <= 0) + { + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + } + if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) + { + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + } + _logger.LogInformation("Pizza. PizzaId:{PizzaId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.EngineId, model.Count, model.Sum, model.Id); + } public bool CreateOrder(OrderBindingModel model) { @@ -72,38 +78,38 @@ namespace MotorPlantBusinessLogic.BusinessLogics } - private bool ChangeStatus(OrderBindingModel model, OrderStatus status) + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) { - var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (element == null) - { - _logger.LogWarning("Find order failed"); - return false; - } - if (element.Status != status - 1) - { - _logger.LogWarning("Status change failed"); - throw new InvalidOperationException("Невозможно перевести состояние заказа"); - } - if (status == OrderStatus.Готов) - { - var engine = _engineStorage.GetElement(new EngineSearchModel() { Id = model.EngineId }); - if (engine == null) - { - _logger.LogWarning("Status change error. Engine not found"); - return false; - } - if (!CheckSupply(engine, model.Count)) - { - _logger.LogWarning("Status change error. Shop doesnt have engines"); - return false; - } - } - model.Status = status; - if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; - _orderStorage.Update(model); - return true; - } + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.EngineId = element.EngineId; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Выдан) + model.DateImplement = DateTime.Now; + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + } public bool TakeOrderInWork(OrderBindingModel model) { @@ -117,67 +123,24 @@ namespace MotorPlantBusinessLogic.BusinessLogics public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); - } + var order = _orderStorage.GetElement(new OrderSearchModel + { + Id = model.Id, + }); + if (order == null) + { + throw new ArgumentNullException(nameof(order)); + } + if (!_shopStorage.RestockingShops(new SupplyBindingModel + { + EngineId = order.EngineId, + Count = order.Count + })) + { + throw new ArgumentException("Недостаточно места"); + } - public bool CheckSupply(IEngineModel engine, int count) - { - if (count <= 0) - { - _logger.LogWarning("Check supply operation error. Engine count < 0"); - return false; - } - int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum(); - int sumCount = _shopStorage.GetFullList().Select(x => x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum(); - int free = sumCapacity - sumCount; - - if (free < count) - { - _logger.LogWarning("Check supply error. No place for new Engines"); - return false; - } - foreach (var shop in _shopStorage.GetFullList()) - { - free = shop.MaxCount; - foreach (var doc in shop.ShopEngines) - { - free -= doc.Value.Item2; - } - if (free == 0) - { - continue; - } - if (free >= count) - { - if (_shopLogic.MakeSupply(new() - { - Id = shop.Id - }, engine, count)) - { - count = 0; - } - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - else - { - if (_shopLogic.MakeSupply(new() { Id = shop.Id }, engine, free)) - count -= free; - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - if (count <= 0) - { - return true; - } - } - return false; - } + return ChangeStatus(model, OrderStatus.Выдан); + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs index 9483f6d..a9e051d 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs @@ -1,15 +1,10 @@ -using MotorPlantBusinessLogic.OfficePackage.HelperModels; -using MotorPlantBusinessLogic.OfficePackage; +using MotorPlantBusinessLogic.OfficePackage; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace MotorPlantBusinessLogic.BusinessLogic { @@ -17,22 +12,25 @@ namespace MotorPlantBusinessLogic.BusinessLogic { private readonly IComponentStorage _componentStorage; - private readonly IEngineStorage _engineStorage; + private readonly IEngineStorage _engineStorage; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToPdf _saveToPdf; - public ReportLogic(IEngineStorage engineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, + public ReportLogic(IEngineStorage engineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _engineStorage = engineStorage; - _componentStorage = componentStorage; - _orderStorage = orderStorage; + _componentStorage = componentStorage; + _orderStorage = orderStorage; + _shopStorage = shopStorage; _saveToExcel = saveToExcel; _saveToWord = saveToWord; @@ -42,28 +40,12 @@ namespace MotorPlantBusinessLogic.BusinessLogic public List GetEngineComponents() { - var engines = _engineStorage.GetFullList(); - - var list = new List(); - - foreach (var engine in engines) + return _engineStorage.GetFullList().Select(x => new ReportEngineComponentViewModel { - var record = new ReportEngineComponentViewModel - { - EngineName = engine.EngineName, - Components = new List<(string Component, int Count)>(), - TotalCount = 0, - }; - foreach (var component in engine.EngineComponents) - { - record.Components.Add(new(component.Value.Item1.ComponentName, component.Value.Item2)); - record.TotalCount += component.Value.Item2; - } - - list.Add(record); - } - - return list; + EngineName = x.EngineName, + Components = x.EngineComponents.Select(x => (x.Value.Item1.ComponentName, x.Value.Item2)).ToList(), + TotalCount = x.EngineComponents.Select(x => x.Value.Item2).Sum() + }).ToList(); } public List GetOrders(ReportBindingModel model) @@ -111,5 +93,55 @@ namespace MotorPlantBusinessLogic.BusinessLogic Orders = GetOrders(model) }); } + + public List GetShops() + { + return _shopStorage.GetFullList().Select(x => new ReportShopsViewModel + { + ShopName = x.ShopName, + Engines = x.ShopEngines.Select(x => (x.Value.Item1.EngineName, x.Value.Item2)).ToList(), + TotalCount = x.ShopEngines.Select(x => x.Value.Item2).Sum() + }).ToList(); + } + + public List GetGroupedOrders() + { + return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportGroupOrdersViewModel + { + Date = x.Key, + OrdersCount = x.Count(), + OrdersSum = x.Select(y => y.Sum).Sum() + }).ToList(); + } + + public void SaveShopsToWordFile(ReportBindingModel model) + { + _saveToWord.CreateShopsDoc(new WordShopInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + + public void SaveShopsToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopEnginesReport(new ExcelShop + { + FileName = model.FileName, + Title = "Наполненость магазинов", + ShopEngines = GetShops() + }); + } + + public void SaveGroupedOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateGroupedOrdersDoc(new PdfGroupedOrdersInfo + { + FileName = model.FileName, + Title = "Список заказов сгруппированных по дате заказов", + GroupedOrders = GetGroupedOrders() + }); + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs index 35e65a1..a645ef6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -17,11 +17,13 @@ namespace MotorPlantBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IShopStorage _shopStorage; + private readonly IEngineStorage _engineStorage; - public ShopLogic(ILogger logger, IShopStorage shopStorage) + public ShopLogic(ILogger logger, IShopStorage shopStorage, IEngineStorage engineStorage) { _logger = logger; _shopStorage = shopStorage; + _engineStorage = engineStorage; } public List ReadList(ShopSearchModel model) @@ -75,6 +77,7 @@ namespace MotorPlantBusinessLogic.BusinessLogic } return true; } + public bool Delete(ShopBindingModel model) { CheckModel(model, false); @@ -123,52 +126,70 @@ namespace MotorPlantBusinessLogic.BusinessLogic } } - public bool MakeSell(IEngineModel model, int count) - { - return _shopStorage.SellEngines(model, count); - } - - public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) + public bool MakeSupply(SupplyBindingModel model) { - if (model == null) - throw new ArgumentNullException(nameof(model)); - if (engine == null) - throw new ArgumentNullException(nameof(engine)); - if (count <= 0) - throw new ArgumentNullException("Количество должно быть положительным числом"); + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество движков должно быть больше 0"); + } + var shop = _shopStorage.GetElement(new ShopSearchModel + { + Id = model.ShopId + }); + if (shop == null) + { + throw new ArgumentException("Магазина не существует"); + } + if (shop.ShopEngines.ContainsKey(model.EngineId)) + { + var oldValue = shop.ShopEngines[model.EngineId]; + oldValue.Item2 += model.Count; + shop.ShopEngines[model.EngineId] = oldValue; + } + else + { + var pizza = _engineStorage.GetElement(new EngineSearchModel + { + Id = model.EngineId + }); + if (pizza == null) + { + throw new ArgumentException($"Поставка: Товар с id:{model.EngineId} не найденн"); + } + shop.ShopEngines.Add(model.EngineId, (pizza, model.Count)); + } - ShopViewModel? curModel = _shopStorage.GetElement(model); - _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); - if (curModel == null) - throw new ArgumentNullException(nameof(curModel)); + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + DateOpen = shop.DateOpen, + ShopEngines = shop.ShopEngines, + MaxCount = shop.MaxCount, + }); - var countItems = curModel.ShopEngines.Select(x => x.Value.Item2).Sum(); - if (curModel.MaxCount - countItems < count) - { - _logger.LogWarning("Shop is overflowed"); - return false; - } + return true; + } - if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) - { - curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); - _logger.LogInformation("Make Supply. Add Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count + pair.Item2); - } - else - { - curModel.ShopEngines.Add(engine.Id, (engine, count)); - _logger.LogInformation("Make Supply. Add new Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count); - } - - return Update(new() - { - Id = curModel.Id, - ShopName = curModel.ShopName, - DateOpen = curModel.DateOpen, - MaxCount = curModel.MaxCount, - Adress = curModel.Adress, - ShopEngines = curModel.ShopEngines, - }); - } + public bool MakeSell(SupplySearchModel model) + { + if (!model.EngineId.HasValue || !model.Count.HasValue) + { + return false; + } + _logger.LogInformation("Check pizza count in all shops"); + if (_shopStorage.SellEngines(model)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs index 30ff911..819aae3 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -84,28 +84,81 @@ namespace MotorPlantBusinessLogic.OfficePackage SaveExcel(info); } - /// - /// Создание excel-файла - /// - /// - protected abstract void CreateExcel(ExcelInfo info); + public void CreateShopEnginesReport(ExcelShop info) + { + CreateExcel(info); - /// - /// Добавляем новую ячейку в лист - /// - /// + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + uint rowIndex = 2; + foreach (var sr in info.ShopEngines) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = sr.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Engine, Count) in sr.Engines) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Engine, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = sr.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(info); + } + + protected abstract void CreateExcel(IDocument info); protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); - - /// - /// Объединение ячеек - /// - /// protected abstract void MergeCells(ExcelMergeParameters excelParams); - - /// - /// Сохранение файла - /// - /// - protected abstract void SaveExcel(ExcelInfo info); + protected abstract void SaveExcel(IDocument info); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index b746823..1611779 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -48,11 +48,40 @@ namespace MotorPlantBusinessLogic.OfficePackage SavePdf(info); } + public void CreateGroupedOrdersDoc(PdfGroupedOrdersInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "4cm", "3cm", "2cm" }); + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата заказа", "Кол-во", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + + foreach (var groupedOrder in info.GroupedOrders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { groupedOrder.Date.ToShortDateString(), groupedOrder.OrdersCount.ToString(), groupedOrder.OrdersSum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.OrdersSum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + SavePdf(info); + } + /// /// Создание pdf-файла /// /// - protected abstract void CreatePdf(PdfInfo info); + protected abstract void CreatePdf(IDocument info); /// /// Создание параграфа с текстом @@ -78,6 +107,6 @@ namespace MotorPlantBusinessLogic.OfficePackage /// Сохранение файла /// /// - protected abstract void SavePdf(PdfInfo info); + protected abstract void SavePdf(IDocument info); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs index 33a498c..7223858 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -41,23 +41,51 @@ namespace MotorPlantBusinessLogic.OfficePackage SaveWord(info); } - /// - /// Создание doc-файла - /// - /// - protected abstract void CreateWord(WordInfo info); + public void CreateShopsDoc(WordShopInfo info) + { + CreateWord(info); + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); - /// - /// Создание абзаца с текстом - /// - /// - /// + CreateTable(new List { "3000", "3000", "3000" }); + CreateRow(new WordRowParameters + { + Texts = new List { "Название", "Адрес", "Дата открытия" }, + TextProperties = new WordTextProperties + { + Size = "24", + Bold = true, + JustificationType = WordJustificationType.Center + } + }); + + foreach (var shop in info.Shops) + { + CreateRow(new WordRowParameters + { + Texts = new List { shop.ShopName, shop.Adress, shop.DateOpen.ToString() }, + TextProperties = new WordTextProperties + { + Size = "22", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + protected abstract void CreateWord(IDocument info); protected abstract void CreateParagraph(WordParagraph paragraph); - - /// - /// Сохранение файла - /// - /// - protected abstract void SaveWord(WordInfo info); + protected abstract void SaveWord(IDocument info); + protected abstract void CreateTable(List colums); + protected abstract void CreateRow(WordRowParameters rowParameters); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs index 71b04fb..c32d036 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace MotorPlantBusinessLogic.OfficePackage.HelperModels { - public class ExcelInfo + public class ExcelInfo : IDocument { public string FileName { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs new file mode 100644 index 0000000..600eecf --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs @@ -0,0 +1,11 @@ +using MotorPlantContracts.ViewModels; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelShop : IDocument + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public List ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs new file mode 100644 index 0000000..75c655a --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs @@ -0,0 +1,13 @@ +using MotorPlantContracts.ViewModels; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class PdfGroupedOrdersInfo : IDocument + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public DateTime DateFrom { get; set; } + public DateTime DateTo { get; set; } + public List GroupedOrders { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs index 308fbe9..f919683 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace MotorPlantBusinessLogic.OfficePackage.HelperModels { - public class PdfInfo + public class PdfInfo : IDocument { public string FileName { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index 2589b0c..0a03ba5 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace MotorPlantBusinessLogic.OfficePackage.HelperModels { - public class WordInfo + public class WordInfo : IDocument { public string FileName { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs new file mode 100644 index 0000000..7cb81a9 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class WordRowParameters + { + public List Texts { get; set; } = new(); + public WordTextProperties TextProperties { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs new file mode 100644 index 0000000..f781da1 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs @@ -0,0 +1,16 @@ +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class WordShopInfo : IDocument + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public List Shops { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs new file mode 100644 index 0000000..1076a82 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage +{ + public interface IDocument + { + public string FileName { get; set; } + public string Title { get; set; } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs index 12f3ef8..3808437 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -151,7 +151,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements }; } - protected override void CreateExcel(ExcelInfo info) + protected override void CreateExcel(IDocument info) { _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); // Создаем книгу (в ней хранятся листы) @@ -280,7 +280,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements mergeCells.Append(mergeCell); } - protected override void SaveExcel(ExcelInfo info) + protected override void SaveExcel(IDocument info) { if (_spreadsheetDocument == null) { diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs index 238d541..f1d91ab 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -34,7 +34,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements style.Font.Bold = true; } - protected override void CreatePdf(PdfInfo info) + protected override void CreatePdf(IDocument info) { _document = new Document(); DefineStyles(_document); @@ -96,7 +96,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements } } - protected override void SavePdf(PdfInfo info) + protected override void SavePdf(IDocument info) { var renderer = new PdfDocumentRenderer(true) { diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs index 1c4ea71..b3f15f6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs @@ -81,7 +81,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements return properties; } - protected override void CreateWord(WordInfo info) + protected override void CreateWord(IDocument info) { _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); @@ -119,7 +119,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements _docBody.AppendChild(docParagraph); } - protected override void SaveWord(WordInfo info) + protected override void SaveWord(IDocument info) { if (_docBody == null || _wordDocument == null) { @@ -131,5 +131,77 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements _wordDocument.Dispose(); } + + private Table? _lastTable; + protected override void CreateTable(List columns) + { + if (_docBody == null) + return; + + _lastTable = new Table(); + + var tableProp = new TableProperties(); + tableProp.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); + tableProp.AppendChild(new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } + )); + tableProp.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); + _lastTable.AppendChild(tableProp); + + TableGrid tableGrid = new TableGrid(); + foreach (var column in columns) + { + tableGrid.AppendChild(new GridColumn() { Width = column }); + } + _lastTable.AppendChild(tableGrid); + + _docBody.AppendChild(_lastTable); + } + + protected override void CreateRow(WordRowParameters rowParameters) + { + if (_docBody == null || _lastTable == null) + return; + + TableRow docRow = new TableRow(); + foreach (var column in rowParameters.Texts) + { + var docParagraph = new Paragraph(); + WordParagraph paragraph = new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (column, rowParameters.TextProperties) }, + TextProperties = rowParameters.TextProperties + }; + + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); + + var properties = new RunProperties(); + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + docRun.AppendChild(properties); + + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); + + docParagraph.AppendChild(docRun); + } + + TableCell docCell = new TableCell(); + docCell.AppendChild(docParagraph); + docRow.AppendChild(docCell); + } + _lastTable.AppendChild(docRow); + } } } diff --git a/MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs new file mode 100644 index 0000000..332cfee --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs @@ -0,0 +1,16 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class SupplyBindingModel : ISupplyModel + { + public int ShopId { get; set; } + public int EngineId { get; set; } + public int Count { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs index d8e7efb..3ca180e 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs @@ -11,13 +11,14 @@ namespace MotorPlantContracts.BusinessLogicsContracts public interface IReportLogic { List GetEngineComponents(); - List GetOrders(ReportBindingModel model); - + List GetShops(); + List GetGroupedOrders(); void SaveEngineToWordFile(ReportBindingModel model); - void SaveEngineComponentToExcelFile(ReportBindingModel model); - void SaveOrdersToPdfFile(ReportBindingModel model); + void SaveShopsToWordFile(ReportBindingModel model); + void SaveShopsToExcelFile(ReportBindingModel model); + void SaveGroupedOrdersToPdfFile(ReportBindingModel model); } } diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs index ce4f7b0..bfa3267 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -14,10 +14,10 @@ namespace MotorPlantContracts.BusinessLogicsContracts { List? ReadList(ShopSearchModel? model); ShopViewModel? ReadElement(ShopSearchModel? model); - bool Create(ShopBindingModel? model); - bool Update(ShopBindingModel? model); - bool Delete(ShopBindingModel? model); - bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); - bool MakeSell(IEngineModel model, int count); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(SupplyBindingModel model); + bool MakeSell(SupplySearchModel model); } } diff --git a/MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs new file mode 100644 index 0000000..b7dc7e7 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class SupplySearchModel + { + public int? EngineId { get; set; } + public int? Count { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs index 0fb2755..a0369c0 100644 --- a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -18,6 +18,7 @@ namespace MotorPlantContracts.StoragesContracts ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model); - bool SellEngines(IEngineModel model, int count); - } + bool SellEngines(SupplySearchModel model); + bool RestockingShops(SupplyBindingModel model); + } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs new file mode 100644 index 0000000..8c98eee --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ReportGroupOrdersViewModel + { + public DateTime Date { get; set; } = DateTime.Now; + public int OrdersCount { get; set; } + public double OrdersSum { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs new file mode 100644 index 0000000..747752d --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs @@ -0,0 +1,9 @@ +namespace MotorPlantContracts.ViewModels +{ + public class ReportShopsViewModel + { + public string ShopName { get; set; } = string.Empty; + public int TotalCount { get; set; } + public List<(string Engine, int count)> Engines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs b/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..f243749 --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int EngineId { get; } + int Count { get; } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs index f198b99..25fd2e5 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs @@ -13,10 +13,8 @@ namespace MotorPlantDatabaseImplement.Implements public List GetFullList() { using var context = new MotorPlantDatabase(); - return context.Orders - .Select(x => AccessEngineStorage(x.GetViewModel)) - .ToList(); - } + return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList(); + } public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue && !model.DateFrom.HasValue) @@ -24,8 +22,6 @@ namespace MotorPlantDatabaseImplement.Implements return new(); } using var context = new MotorPlantDatabase(); - return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); - } if (model.DateFrom.HasValue) { return context.Orders @@ -42,66 +38,58 @@ namespace MotorPlantDatabaseImplement.Implements } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - using var context = new MotorPlantDatabase(); - return AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); - } + if (!model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return context.Orders.Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - using var context = new MotorPlantDatabase(); - context.Orders.Add(newOrder); - context.SaveChanges(); - return AccessEngineStorage(newOrder.GetViewModel); - } + using var context = new MotorPlantDatabase(); + if (model == null) + return null; + var newOrder = Order.Create(context, model); + if (newOrder == null) + { + return null; + } + context.Orders.Add(newOrder); + context.SaveChanges(); + return newOrder.GetViewModel; + } public OrderViewModel? Update(OrderBindingModel model) { - using var context = new MotorPlantDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == - model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return AccessEngineStorage(order.GetViewModel); - } - - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new MotorPlantDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Orders.Remove(element); - context.SaveChanges(); - return AccessEngineStorage(element.GetViewModel); - } - return null; - } - - public static OrderViewModel AccessEngineStorage(OrderViewModel model) - { - if (model == null) - return null; - using var context = new MotorPlantDatabase(); - foreach (var Engine in context.Engines) - { - if (Engine.Id == model.EngineId) - { - model.EngineName = Engine.EngineName; - break; - } - } - return model; - } - } + using var context = new MotorPlantDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + return null; + } + order.Update(model); + context.SaveChanges(); + return context.Orders + .Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + } + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + var deletedElement = context.Orders + .Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + context.Orders.Remove(element); + context.SaveChanges(); + return deletedElement; + } + return null; + } + } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs index 5772557..9984575 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs @@ -84,61 +84,117 @@ namespace MotorPlantDatabaseImplement.Implements public ShopViewModel? Update(ShopBindingModel model) { - using var context = new MotorPlantDatabase(); - var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); - if (shop == null) - { - return null; - } - try - { - if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) - { - throw new Exception("Не должно быть два магазина с одним названием"); - } - shop.Update(model); - shop.UpdateDresses(context, model); - context.SaveChanges(); - return shop.GetViewModel; - } - catch - { - throw; - } - } - public bool SellEngines(IEngineModel model, int count) + using var context = new MotorPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdateEngines(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool RestockingShops(SupplyBindingModel model) + { + using var context = new MotorPlantDatabase(); + var transaction = context.Database.BeginTransaction(); + var Shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList(). + Where(x => x.MaxCount > x.ShopEngines.Select(x => x.Value.Item2).Sum()).ToList(); + if (model == null) + { + return false; + } + try + { + foreach (Shop shop in Shops) + { + int difference = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum(); + int refill = Math.Min(difference, model.Count); + model.Count -= refill; + if (shop.ShopEngines.ContainsKey(model.EngineId)) + { + var datePair = shop.ShopEngines[model.EngineId]; + datePair.Item2 += refill; + shop.ShopEngines[model.EngineId] = datePair; + } + else + { + var pizza = context.Engines.First(x => x.Id == model.EngineId); + shop.ShopEngines.Add(model.EngineId, (pizza, refill)); + } + shop.EnginesDictionatyUpdate(context); + if (model.Count == 0) + { + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool SellEngines(SupplySearchModel model) { - if (model == null) - return false; - using var context = new MotorPlantDatabase(); - using var transaction = context.Database.BeginTransaction(); - List lst = new List(); - foreach (var el in context.ShopEngines.Where(x => x.EngineId == model.Id)) - { - int dif = count; - if (el.Count < dif) - dif = el.Count; - el.Count -= dif; - count -= dif; - if (el.Count == 0) - { - lst.Add(el); - } - if (count == 0) - break; - } - if (count > 0) - { - transaction.Rollback(); - return false; - } - foreach (var el in lst) - { - context.ShopEngines.Remove(el); - } - context.SaveChanges(); - transaction.Commit(); - return true; - } + using var context = new MotorPlantDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList(). + Where(x => x.ShopEngines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.ShopEngines[model.EngineId.Value].Item2).ToList(); + + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.ShopEngines[model.EngineId.Value].Item2; + if (residue > 0) + { + shop.ShopEngines.Remove(model.EngineId.Value); + shop.EnginesDictionatyUpdate(context); + context.SaveChanges(); + model.Count = residue; + + } + else + { + if (residue == 0) + shop.ShopEngines.Remove(model.EngineId.Value); + else + { + var dataPair = shop.ShopEngines[model.EngineId.Value]; + dataPair.Item2 = -residue; + shop.ShopEngines[model.EngineId.Value] = dataPair; + } + + shop.EnginesDictionatyUpdate(context); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs new file mode 100644 index 0000000..b967a0f --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs @@ -0,0 +1,246 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MotorPlantDatabaseImplement; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace MotorPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(MotorPlantDatabase))] + [Migration("20240516204547_ThirdMigtation")] + partial class ThirdMigtation + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.16") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Cost") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EngineName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("Engines"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("integer"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("EngineId"); + + b.ToTable("EngineComponents"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("DateCreate") + .HasColumnType("timestamp without time zone"); + + b.Property("DateImplement") + .HasColumnType("timestamp without time zone"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Sum") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateOpen") + .HasColumnType("timestamp without time zone"); + + b.Property("MaxCount") + .HasColumnType("integer"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("ShopId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopEngines"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") + .WithMany("EngineComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany("Components") + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Engine"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) + .WithMany("Orders") + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany() + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Engines") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Engine"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("EngineComponents"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Engines"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs similarity index 99% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs index 5a17410..9cf9cab 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { /// - public partial class NewMig : Migration + public partial class ThirdMigtation : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 7355218..5c6bc31 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -12,7 +12,7 @@ namespace MotorPlantDatabaseImplement.Models [Required] public int EngineId { get; private set; } - + public virtual Engine Engine { get; set; } = new(); [Required] public int Count { get; private set; } @@ -27,16 +27,13 @@ namespace MotorPlantDatabaseImplement.Models public DateTime? DateImplement { get; private set; } - public static Order? Create(OrderBindingModel? model) + public static Order Create(MotorPlantDatabase context, OrderBindingModel model) { - if (model == null) - { - return null; - } return new Order() { Id = model.Id, EngineId = model.EngineId, + Engine = context.Engines.First(x => x.Id == model.EngineId), Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -58,6 +55,7 @@ namespace MotorPlantDatabaseImplement.Models { Id = Id, EngineId = EngineId, + EngineName = Engine.EngineName, Count = Count, Sum = Sum, Status = Status, diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs index 1aa014d..7eda723 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs @@ -15,16 +15,16 @@ namespace MotorPlantDatabaseImplement.Models { public int Id { get; private set; } [Required] - public string ShopName { get; private set; } - [Required] - public string Adress { get; private set; } - [Required] + public string ShopName { get; private set; } = string.Empty; + [Required] + public string Adress { get; private set; } = string.Empty; + [Required] public DateTime DateOpen { get; private set; } [Required] public int MaxCount { get; private set; } private Dictionary? _shopEngines = null; [NotMapped] - public Dictionary? ShopEngines + public Dictionary ShopEngines { get { @@ -74,7 +74,7 @@ namespace MotorPlantDatabaseImplement.Models ShopEngines = ShopEngines }; - public void UpdateDresses(MotorPlantDatabase context, ShopBindingModel model) + public void UpdateEngines(MotorPlantDatabase context, ShopBindingModel model) { var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); if (shopEngines != null && shopEngines.Count > 0) @@ -101,5 +101,14 @@ namespace MotorPlantDatabaseImplement.Models } _shopEngines = null; } - } + + public void EnginesDictionatyUpdate(MotorPlantDatabase context) + { + UpdateEngines(context, new ShopBindingModel + { + Id = Id, + ShopEngines = ShopEngines, + }); + } + } } diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs index 29ae922..ae401af 100644 --- a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -75,44 +75,73 @@ namespace MotorPlantFileImplement.Implements return null; } - public bool SellEngines(IEngineModel model, int count) + public bool SellEngines(SupplySearchModel model) { - var eng = _source.Engines.FirstOrDefault(x => x.Id == model.Id); - int store = _source.Shops.SelectMany(x => x.ShopEngines).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); + if (model == null || !model.EngineId.HasValue || !model.Count.HasValue) + return false; + int remainingSpace = _source.Shops.Select(x => x.Engines.ContainsKey(model.EngineId.Value) ? x.Engines[model.EngineId.Value] : 0).Sum(); + if (remainingSpace < model.Count) + { + return false; + } + var shops = _source.Shops.Where(x => x.Engines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.Engines[model.EngineId.Value]).ToList(); + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.Engines[model.EngineId.Value]; + if (residue > 0) + { + shop.Engines.Remove(model.EngineId.Value); + shop.EngineUpdate(); + model.Count = residue; + } + else + { + if (residue == 0) + { + shop.Engines.Remove(model.EngineId.Value); + } + else + { + shop.Engines[model.EngineId.Value] = -residue; + } + shop.EngineUpdate(); + _source.SaveShops(); + return true; + } + } + _source.SaveShops(); + return false; + } - if (eng == null || store < count) - { - return false; - } - - for (int i = 0; i < _source.Shops.Count; i++) - { - var shop = _source.Shops[i]; - var engines = shop.ShopEngines; - foreach (var engine in engines.Where(x => x.Value.Item1.Id == eng.Id)) - { - var selling = Math.Min(engine.Value.Item2, count); - engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); - - count -= selling; - - if (count <= 0) - { - break; - } - } - shop.Update(new ShopBindingModel - { - Id = model.Id, - ShopName = shop.ShopName, - Adress = shop.Adress, - MaxCount = shop.MaxCount, - DateOpen = shop.DateOpen, - ShopEngines = engines - }); - } - _source.SaveShops(); - return true; - } - } + public bool RestockingShops(SupplyBindingModel model) + { + if (model == null || _source.Shops.Select(x => x.MaxCount - x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum() < model.Count) + { + return false; + } + foreach (Shop shop in _source.Shops) + { + int free_places = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum(); + if (free_places <= 0) + continue; + free_places = Math.Min(free_places, model.Count); + model.Count -= free_places; + if (shop.Engines.ContainsKey(model.EngineId)) + { + shop.Engines[model.EngineId] += free_places; + } + else + { + shop.Engines.Add(model.EngineId, free_places); + } + shop.EngineUpdate(); + if (model.Count == 0) + { + _source.SaveShops(); + return true; + } + } + return false; + } + } } diff --git a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs index 98d151d..8c17a87 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs @@ -98,5 +98,10 @@ namespace MotorPlantFileImplement.Models new XElement("DateOpen", DateOpen), new XElement("MaxCount", MaxCount), new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); - } + + public void EngineUpdate() + { + _shopEngines = null; + } + } } diff --git a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs index a973288..efc5ebb 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs @@ -31,7 +31,7 @@ namespace MotorPlantListImplement.Implements public List GetFilteredList(OrderSearchModel model) { var result = new List(); - if (model == null || !model.Id.HasValue) + if (model == null) { return result; } diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs index 2d61dae..c52700e 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -108,9 +108,14 @@ namespace MotorPlantListImplement.Implements { return true; } - public bool SellEngines(IEngineModel model, int count) + public bool SellEngines(SupplySearchModel model) { - return true; - } - } + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } } diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index b4652b7..a68b404 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,26 +1,26 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify @@ -32,10 +32,16 @@ toolStripDropDownButton1 = new ToolStripDropDownButton(); Компоненты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(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); @@ -59,7 +65,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, магазиныToolStripMenuItem, поставкаToolStripMenuItem, продажаToolStripMenuItem }); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; toolStripDropDownButton1.Size = new Size(88, 22); @@ -79,9 +85,30 @@ ДвигателиToolStripMenuItem.Text = "Двигатели"; ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(145, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; + // + // поставкаToolStripMenuItem + // + поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem"; + поставкаToolStripMenuItem.Size = new Size(145, 22); + поставкаToolStripMenuItem.Text = "Поставка"; + поставкаToolStripMenuItem.Click += поставкаToolStripMenuItem_Click; + // + // продажаToolStripMenuItem + // + продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; + продажаToolStripMenuItem.Size = new Size(145, 22); + продажаToolStripMenuItem.Text = "Продажа"; + продажаToolStripMenuItem.Click += продажаToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, загруженностьМагазиновToolStripMenuItem, заказыПоГруппамToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 25); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -107,6 +134,27 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // списокМагазиновToolStripMenuItem + // + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(228, 22); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click; + // + // загруженностьМагазиновToolStripMenuItem + // + загруженностьМагазиновToolStripMenuItem.Name = "загруженностьМагазиновToolStripMenuItem"; + загруженностьМагазиновToolStripMenuItem.Size = new Size(228, 22); + загруженностьМагазиновToolStripMenuItem.Text = "Загруженность магазинов"; + загруженностьМагазиновToolStripMenuItem.Click += загруженностьМагазиновToolStripMenuItem_Click; + // + // заказыПоГруппамToolStripMenuItem + // + заказыПоГруппамToolStripMenuItem.Name = "заказыПоГруппамToolStripMenuItem"; + заказыПоГруппамToolStripMenuItem.Size = new Size(228, 22); + заказыПоГруппамToolStripMenuItem.Text = "Заказы по группам"; + заказыПоГруппамToolStripMenuItem.Click += заказыПоГруппамToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -203,7 +251,7 @@ PerformLayout(); } - #endregion + #endregion private ToolStrip toolStrip1; private Button buttonCreateOrder; @@ -219,5 +267,11 @@ private ToolStripMenuItem списокДвигателейToolStripMenuItem; private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem поставкаToolStripMenuItem; + private ToolStripMenuItem продажаToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem загруженностьМагазиновToolStripMenuItem; + private ToolStripMenuItem заказыПоГруппамToolStripMenuItem; } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index a036221..52a92bf 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -18,6 +18,7 @@ namespace MotorPlantView.Forms _orderLogic = orderLogic; _reportLogic = reportLogic; } + private void FormMain_Load(object sender, EventArgs e) { LoadData(); @@ -29,38 +30,41 @@ namespace MotorPlantView.Forms { var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; - } + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + } + } - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); if (service is FormEngines form) { form.ShowDialog(); } } + private void buttonCreateOrder_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); @@ -70,6 +74,7 @@ namespace MotorPlantView.Forms LoadData(); } } + private void buttonTakeOrderInWork_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -95,6 +100,7 @@ namespace MotorPlantView.Forms } } } + private void buttonOrderReady_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -118,6 +124,7 @@ namespace MotorPlantView.Forms } } } + private void buttonIssuedOrder_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -139,10 +146,12 @@ namespace MotorPlantView.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } + private void buttonRef_Click(object sender, EventArgs e) { LoadData(); @@ -175,5 +184,60 @@ namespace MotorPlantView.Forms form.ShowDialog(); } } + + private void поставкаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + if (service is FormSupply form) + { + form.ShowDialog(); + } + } + + private void продажаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (service is FormSell form) + { + form.ShowDialog(); + } + } + + private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + private void загруженностьМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShop)); + if (service is FormReportShop form) + { + form.ShowDialog(); + } + } + + private void заказыПоГруппамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders)); + if (service is FormReportGroupedOrders form) + { + form.ShowDialog(); + } + } + + private void магазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } } } diff --git a/MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs b/MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs new file mode 100644 index 0000000..4c22887 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs @@ -0,0 +1,86 @@ +namespace MotorPlantView +{ + partial class FormReportGroupedOrders + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + this.panel = new System.Windows.Forms.Panel(); + this.buttonToPDF = new System.Windows.Forms.Button(); + this.buttonMake = new System.Windows.Forms.Button(); + this.panel.SuspendLayout(); + this.SuspendLayout(); + // + // panel + // + this.panel.Controls.Add(this.buttonToPDF); + this.panel.Controls.Add(this.buttonMake); + this.panel.Dock = System.Windows.Forms.DockStyle.Top; + this.panel.Location = new System.Drawing.Point(0, 0); + this.panel.Name = "panel"; + this.panel.Size = new System.Drawing.Size(970, 52); + this.panel.TabIndex = 1; + // + // buttonToPDF + // + this.buttonToPDF.Location = new System.Drawing.Point(486, 12); + this.buttonToPDF.Name = "buttonToPDF"; + this.buttonToPDF.Size = new System.Drawing.Size(411, 29); + this.buttonToPDF.TabIndex = 5; + this.buttonToPDF.Text = "В PDF"; + this.buttonToPDF.UseVisualStyleBackColor = true; + this.buttonToPDF.Click += new System.EventHandler(this.buttonToPDF_Click); + // + // buttonMake + // + this.buttonMake.Location = new System.Drawing.Point(49, 12); + this.buttonMake.Name = "buttonMake"; + this.buttonMake.Size = new System.Drawing.Size(377, 29); + this.buttonMake.TabIndex = 4; + this.buttonMake.Text = "Сформировать"; + this.buttonMake.UseVisualStyleBackColor = true; + this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click); + // + // FormReportGroupedOrders + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(970, 450); + this.Controls.Add(this.panel); + this.Name = "FormReportGroupedOrders"; + this.Text = "Отчёт по группированным заказам "; + this.panel.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private Panel panel; + private Button buttonToPDF; + private Button buttonMake; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportGroupedOrders.cs b/MotorPlant/MotorPlantView/FormReportGroupedOrders.cs new file mode 100644 index 0000000..8b0e34f --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportGroupedOrders.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView +{ + public partial class FormReportGroupedOrders : Form + { + private readonly ReportViewer reportViewer; + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportGroupedOrders(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + reportViewer = new ReportViewer + { + Dock = DockStyle.Fill + }; + reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\salih\\OneDrive\\Рабочий стол\\MotorPlant\\MotorPlant\\MotorPlantView\\ReportGroupedOrders.rdlc", FileMode.Open)); + Controls.Clear(); + Controls.Add(reportViewer); + Controls.Add(panel); + } + + private void ButtonMake_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetGroupedOrders(); + var source = new ReportDataSource("DataSetGroupedOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + + reportViewer.RefreshReport(); + _logger.LogInformation("Загрузка списка группированных заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка группированных заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + + private void buttonToPDF_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveGroupedOrdersToPdfFile(new ReportBindingModel + { + FileName = dialog.FileName, + }); + _logger.LogInformation("Сохранение списка группированных заказов"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка группированных заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportGroupedOrders.resx b/MotorPlant/MotorPlantView/FormReportGroupedOrders.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportGroupedOrders.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportShop.Designer.cs b/MotorPlant/MotorPlantView/FormReportShop.Designer.cs new file mode 100644 index 0000000..2e36897 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.Designer.cs @@ -0,0 +1,116 @@ +namespace MotorPlantView +{ + partial class FormReportShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #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() + { + this.buttonSaveToExcel = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ColumnShop = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnPizza = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // buttonSaveToExcel + // + this.buttonSaveToExcel.Location = new System.Drawing.Point(0, 6); + this.buttonSaveToExcel.Name = "buttonSaveToExcel"; + this.buttonSaveToExcel.Size = new System.Drawing.Size(223, 29); + this.buttonSaveToExcel.TabIndex = 3; + this.buttonSaveToExcel.Text = "Сохранить в Excel"; + this.buttonSaveToExcel.UseVisualStyleBackColor = true; + this.buttonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.AllowUserToOrderColumns = true; + this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.ColumnShop, + this.ColumnPizza, + this.ColumnCount}); + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Bottom; + this.dataGridView.Location = new System.Drawing.Point(0, 47); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(598, 403); + this.dataGridView.TabIndex = 2; + // + // ColumnShop + // + this.ColumnShop.FillWeight = 130F; + this.ColumnShop.HeaderText = "Магазин"; + this.ColumnShop.MinimumWidth = 6; + this.ColumnShop.Name = "ColumnShop"; + this.ColumnShop.ReadOnly = true; + // + // ColumnPizza + // + this.ColumnPizza.FillWeight = 140F; + this.ColumnPizza.HeaderText = "Пицца"; + this.ColumnPizza.MinimumWidth = 6; + this.ColumnPizza.Name = "ColumnPizza"; + this.ColumnPizza.ReadOnly = true; + // + // ColumnCount + // + this.ColumnCount.FillWeight = 90F; + this.ColumnCount.HeaderText = "Количество"; + this.ColumnCount.MinimumWidth = 6; + this.ColumnCount.Name = "ColumnCount"; + this.ColumnCount.ReadOnly = true; + // + // FormReportShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(598, 450); + this.Controls.Add(this.buttonSaveToExcel); + this.Controls.Add(this.dataGridView); + this.Name = "FormReportShop"; + this.Text = "Наполненость магазинов"; + this.Load += new System.EventHandler(this.FormReportShop_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button buttonSaveToExcel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnShop; + private DataGridViewTextBoxColumn ColumnPizza; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportShop.cs b/MotorPlant/MotorPlantView/FormReportShop.cs new file mode 100644 index 0000000..b6d1130 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView +{ + public partial class FormReportShop : Form + { + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportShop(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormReportShop_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShops(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Engines) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Загрузка списка пицц по магазинам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка пицц по магазинам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopsToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка пицц по магазинам"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка пицц по магазинам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportShop.resx b/MotorPlant/MotorPlantView/FormReportShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSell.cs b/MotorPlant/MotorPlantView/FormSell.cs index 09d47ad..a434303 100644 --- a/MotorPlant/MotorPlantView/FormSell.cs +++ b/MotorPlant/MotorPlantView/FormSell.cs @@ -10,6 +10,7 @@ using System.Windows.Forms; using MotorPlantDataModels.Models; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.ViewModels; +using MotorPlantContracts.SearchModels; namespace MotorPlantView { @@ -73,44 +74,34 @@ namespace MotorPlantView private void buttonSave_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCount.Text)) - { - MessageBox.Show("Заполните поле Количество", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (comboBoxEngine.SelectedValue == null) - { - MessageBox.Show("Выберите двигатель", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - - try - { - int count = Convert.ToInt32(textBoxCount.Text); - - bool res = _shopLogic.MakeSell( - _engineLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxEngine.SelectedValue) }), - count - ); - - if (!res) - { - throw new Exception("Ошибка при продаже."); - } - - MessageBox.Show("Продажа прошла успешно"); - DialogResult = DialogResult.OK; - Close(); - - } - catch (Exception err) - { - MessageBox.Show("Ошибка продажи"); - return; - } - } + if (comboBoxEngine.SelectedValue == null) + { + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + bool resout = _shopLogic.MakeSell(new SupplySearchModel + { + EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (resout) + { + MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + else + { + MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } private void buttonCancel_Click(object sender, EventArgs e) { diff --git a/MotorPlant/MotorPlantView/FormSupply.cs b/MotorPlant/MotorPlantView/FormSupply.cs index fa59e52..aa0174d 100644 --- a/MotorPlant/MotorPlantView/FormSupply.cs +++ b/MotorPlant/MotorPlantView/FormSupply.cs @@ -1,4 +1,5 @@ -using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; @@ -85,49 +86,35 @@ namespace MotorPlantView private void SaveButton_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(CountTextBox.Text)) + if (ShopComboBox.SelectedValue == null) { - MessageBox.Show("Заполните поле Количество", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (EngineComboBox.SelectedValue == null) { - MessageBox.Show("Выберите двигатель", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - if (ShopComboBox.SelectedValue == null) - { - MessageBox.Show("Выберите магазин", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - try { - int count = Convert.ToInt32(CountTextBox.Text); - - bool res = _shopLogic.MakeSupply( - new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, - _engineLogic.ReadElement(new() { Id = Convert.ToInt32(EngineComboBox.SelectedValue) }), - count - ); - - if (!res) + var operationResult = _shopLogic.MakeSupply(new SupplyBindingModel { - throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + ShopId = Convert.ToInt32(ShopComboBox.SelectedValue), + EngineId = Convert.ToInt32(EngineComboBox.SelectedValue), + Count = Convert.ToInt32(CountTextBox.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); } - - MessageBox.Show("Пополнение прошло успешно"); + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); - } - catch (Exception er) + catch (Exception ex) { - MessageBox.Show("Ошибка пополнения"); - return; + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index 0ec24fd..fd0e0f1 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -44,10 +44,13 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -59,8 +62,14 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc b/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc new file mode 100644 index 0000000..2ef2b88 --- /dev/null +++ b/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc @@ -0,0 +1,441 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 20791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + PrecastConcretePlantContractsViewModels + /* Local Query */ + + + + Date + System.DateTime + + + OrdersCount + System.Int32 + + + OrdersSum + System.Decimal + + + + PrecastConcretePlantContracts.ViewModels + ReportGroupOrdersViewModel + PrecastConcretePlantContracts.ViewModels.ReportGroupOrdersViewModel, PrecastConcretePlantContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Отчёт по заказам + + + + 0.6cm + 16.51cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + + + + ReportParameterPeriod + 0.6cm + 0.6cm + 16.51cm + 1 + + + 2pt + 2pt + 2pt + 2pt + + + + + + + 3.90406cm + + + 3.97461cm + + + 3.65711cm + + + + + 0.6cm + + + + + true + true + + + + + Дата создания + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Количество заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Общая сумма заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!Date.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrdersCount.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrdersSum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetGroupedOrders + 1.88242cm + 2.68676cm + 1.2cm + 11.53578cm + 2 + + + + + + true + true + + + + + Итого: + + + + 3.29409cm + 8.06542cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!OrdersSum.Value, "DataSetGroupedOrders") + + + + + + + 3.29409cm + 10.70653cm + 0.6cm + 3.48072cm + 4 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in +