From 828ee7d1db5f31e076308c633b74d860cc970f04 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Wed, 21 Feb 2024 01:42:28 +0400 Subject: [PATCH] LabWork01_Basic --- AircraftPlant/AircraftPlant.sln | 26 +- .../AircraftPlantBusinessLogic.csproj | 17 ++ .../BusinessLogics/ComponentLogic.cs | 174 +++++++++++ .../BusinessLogics/OrderLogic.cs | 188 ++++++++++++ .../BusinessLogics/PlaneLogic.cs | 174 +++++++++++ .../AircraftPlantContracts.csproj | 13 + .../BindingModels/ComponentBindingModel.cs | 31 ++ .../BindingModels/OrderBindingModel.cs | 52 ++++ .../BindingModels/PlaneBindingModel.cs | 40 +++ .../IComponentLogic.cs | 52 ++++ .../BusinessLogicsContracts/IOrderLogic.cs | 52 ++++ .../BusinessLogicsContracts/IPlaneLogic.cs | 52 ++++ .../SearchModels/ComponentSearchModel.cs | 25 ++ .../SearchModels/OrderSearchModel.cs | 20 ++ .../SearchModels/PlaneSearchModel.cs | 25 ++ .../StoragesContracts/IComponentStorage.cs | 58 ++++ .../StoragesContracts/IOrderStorage.cs | 58 ++++ .../StoragesContracts/IPlaneStorage.cs | 58 ++++ .../ViewModels/ComponentViewModel.cs | 34 +++ .../ViewModels/OrderViewModel.cs | 65 ++++ .../ViewModels/PlaneViewModel.cs | 43 +++ .../AircraftPlantDataModels.csproj | 9 + .../Enums/OrderStatus.cs | 24 ++ .../Models/IComponentModel.cs | 24 ++ .../AircraftPlantDataModels/Models/IId.cs | 19 ++ .../Models/IOrderModel.cs | 45 +++ .../Models/IPlaneModel.cs | 29 ++ .../AircraftPlantListImplement.csproj | 14 + .../DataListSingleton.cs | 58 ++++ .../Implements/ComponentStorage.cs | 155 ++++++++++ .../Implements/OrderStorage.cs | 154 ++++++++++ .../Implements/PlaneStorage.cs | 154 ++++++++++ .../Models/Component.cs | 77 +++++ .../Models/Order.cs | 106 +++++++ .../Models/Plane.cs | 90 ++++++ .../AircraftPlantView.csproj | 22 ++ .../AircraftPlantView/Form1.Designer.cs | 39 --- AircraftPlant/AircraftPlantView/Form1.cs | 10 - .../FormComponent.Designer.cs | 118 ++++++++ .../AircraftPlantView/FormComponent.cs | 136 +++++++++ .../{Form1.resx => FormComponent.resx} | 50 +-- .../FormComponents.Designer.cs | 122 ++++++++ .../AircraftPlantView/FormComponents.cs | 154 ++++++++++ .../AircraftPlantView/FormComponents.resx | 120 ++++++++ .../FormCreateOrder.Designer.cs | 144 +++++++++ .../AircraftPlantView/FormCreateOrder.cs | 171 +++++++++++ .../AircraftPlantView/FormCreateOrder.resx | 120 ++++++++ .../AircraftPlantView/FormMain.Designer.cs | 179 +++++++++++ AircraftPlant/AircraftPlantView/FormMain.cs | 216 +++++++++++++ AircraftPlant/AircraftPlantView/FormMain.resx | 123 ++++++++ .../AircraftPlantView/FormPlane.Designer.cs | 235 +++++++++++++++ AircraftPlant/AircraftPlantView/FormPlane.cs | 284 ++++++++++++++++++ .../AircraftPlantView/FormPlane.resx | 129 ++++++++ .../FormPlaneComponent.Designer.cs | 119 ++++++++ .../AircraftPlantView/FormPlaneComponent.cs | 122 ++++++++ .../AircraftPlantView/FormPlaneComponent.resx | 120 ++++++++ .../AircraftPlantView/FormPlanes.Designer.cs | 122 ++++++++ AircraftPlant/AircraftPlantView/FormPlanes.cs | 158 ++++++++++ .../AircraftPlantView/FormPlanes.resx | 120 ++++++++ AircraftPlant/AircraftPlantView/Program.cs | 51 +++- AircraftPlant/AircraftPlantView/nlog.config | 15 + 61 files changed, 5338 insertions(+), 76 deletions(-) create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ComponentLogic.cs create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/AircraftPlantContracts.csproj create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/ComponentBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/OrderBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/PlaneBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IComponentLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IOrderLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IPlaneLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/SearchModels/ComponentSearchModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/SearchModels/PlaneSearchModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/StoragesContracts/IComponentStorage.cs create mode 100644 AircraftPlant/AircraftPlantContracts/StoragesContracts/IOrderStorage.cs create mode 100644 AircraftPlant/AircraftPlantContracts/StoragesContracts/IPlaneStorage.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/ComponentViewModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/OrderViewModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/PlaneViewModel.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/AircraftPlantDataModels.csproj create mode 100644 AircraftPlant/AircraftPlantDataModels/Enums/OrderStatus.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/Models/IComponentModel.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/Models/IId.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/Models/IOrderModel.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/Models/IPlaneModel.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/AircraftPlantListImplement.csproj create mode 100644 AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Implements/ComponentStorage.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Implements/PlaneStorage.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Models/Component.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Models/Order.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Models/Plane.cs delete mode 100644 AircraftPlant/AircraftPlantView/Form1.Designer.cs delete mode 100644 AircraftPlant/AircraftPlantView/Form1.cs create mode 100644 AircraftPlant/AircraftPlantView/FormComponent.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormComponent.cs rename AircraftPlant/AircraftPlantView/{Form1.resx => FormComponent.resx} (93%) create mode 100644 AircraftPlant/AircraftPlantView/FormComponents.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormComponents.cs create mode 100644 AircraftPlant/AircraftPlantView/FormComponents.resx create mode 100644 AircraftPlant/AircraftPlantView/FormCreateOrder.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormCreateOrder.cs create mode 100644 AircraftPlant/AircraftPlantView/FormCreateOrder.resx create mode 100644 AircraftPlant/AircraftPlantView/FormMain.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormMain.cs create mode 100644 AircraftPlant/AircraftPlantView/FormMain.resx create mode 100644 AircraftPlant/AircraftPlantView/FormPlane.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormPlane.cs create mode 100644 AircraftPlant/AircraftPlantView/FormPlane.resx create mode 100644 AircraftPlant/AircraftPlantView/FormPlaneComponent.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormPlaneComponent.cs create mode 100644 AircraftPlant/AircraftPlantView/FormPlaneComponent.resx create mode 100644 AircraftPlant/AircraftPlantView/FormPlanes.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormPlanes.cs create mode 100644 AircraftPlant/AircraftPlantView/FormPlanes.resx create mode 100644 AircraftPlant/AircraftPlantView/nlog.config diff --git a/AircraftPlant/AircraftPlant.sln b/AircraftPlant/AircraftPlant.sln index 496ba7e..79a2070 100644 --- a/AircraftPlant/AircraftPlant.sln +++ b/AircraftPlant/AircraftPlant.sln @@ -3,7 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.8.34525.116 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AircraftPlantView", "AircraftPlantView\AircraftPlantView.csproj", "{BD817756-3FEE-4B35-8411-BC0F7CAB5221}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AircraftPlantView", "AircraftPlantView\AircraftPlantView.csproj", "{BD817756-3FEE-4B35-8411-BC0F7CAB5221}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AircraftPlantDataModels", "AircraftPlantDataModels\AircraftPlantDataModels.csproj", "{9C4B909A-B15D-4157-93F8-3C73BB815512}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AircraftPlantContracts", "AircraftPlantContracts\AircraftPlantContracts.csproj", "{6119F2AE-1C47-4F5E-9623-97DDFAEE0FEA}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AircraftPlantBusinessLogic", "AircraftPlantBusinessLogic\AircraftPlantBusinessLogic.csproj", "{6F6FDED9-615A-4272-951B-E1F3B0CC5005}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AircraftPlantListImplement", "AircraftPlantListImplement\AircraftPlantListImplement.csproj", "{C7152B1B-4582-4B31-9F1E-0208118BD9D9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +23,22 @@ Global {BD817756-3FEE-4B35-8411-BC0F7CAB5221}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD817756-3FEE-4B35-8411-BC0F7CAB5221}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD817756-3FEE-4B35-8411-BC0F7CAB5221}.Release|Any CPU.Build.0 = Release|Any CPU + {9C4B909A-B15D-4157-93F8-3C73BB815512}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9C4B909A-B15D-4157-93F8-3C73BB815512}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9C4B909A-B15D-4157-93F8-3C73BB815512}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9C4B909A-B15D-4157-93F8-3C73BB815512}.Release|Any CPU.Build.0 = Release|Any CPU + {6119F2AE-1C47-4F5E-9623-97DDFAEE0FEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6119F2AE-1C47-4F5E-9623-97DDFAEE0FEA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6119F2AE-1C47-4F5E-9623-97DDFAEE0FEA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6119F2AE-1C47-4F5E-9623-97DDFAEE0FEA}.Release|Any CPU.Build.0 = Release|Any CPU + {6F6FDED9-615A-4272-951B-E1F3B0CC5005}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F6FDED9-615A-4272-951B-E1F3B0CC5005}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F6FDED9-615A-4272-951B-E1F3B0CC5005}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F6FDED9-615A-4272-951B-E1F3B0CC5005}.Release|Any CPU.Build.0 = Release|Any CPU + {C7152B1B-4582-4B31-9F1E-0208118BD9D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C7152B1B-4582-4B31-9F1E-0208118BD9D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7152B1B-4582-4B31-9F1E-0208118BD9D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C7152B1B-4582-4B31-9F1E-0208118BD9D9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj new file mode 100644 index 0000000..029f939 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ComponentLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ComponentLogic.cs new file mode 100644 index 0000000..42d137e --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ComponentLogic.cs @@ -0,0 +1,174 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для компонентов + /// + public class ComponentLogic : IComponentLogic + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем компонентов + /// + private readonly IComponentStorage _componentStorage; + + /// + /// Конструктор + /// + /// + /// + public ComponentLogic(ILogger logger, IComponentStorage +componentStorage) + { + _logger = logger; + _componentStorage = componentStorage; + } + + /// + /// Получение списка + /// + /// + /// + public List? ReadList(ComponentSearchModel? model) + { + _logger.LogInformation("ReadList. ComponentName:{ComponentName}.Id:{ Id}", model?.ComponentName, model?.Id); + + var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + /// + /// Получение отдельной записи + /// + /// + /// + /// + public ComponentViewModel? ReadElement(ComponentSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. ComponentName:{ComponentName}.Id:{ Id}", model.ComponentName, model.Id); + + var element = _componentStorage.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(ComponentBindingModel model) + { + CheckModel(model); + + if (_componentStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + /// + /// Изменение записи + /// + /// + /// + public bool Update(ComponentBindingModel model) + { + CheckModel(model); + + if (_componentStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + /// + /// Удаление записи + /// + /// + /// + public bool Delete(ComponentBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_componentStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + /// + /// Проверка модели компонента + /// + /// + /// + private void CheckModel(ComponentBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ComponentName)) + { + throw new ArgumentNullException("Нет названия компонента", nameof(model.ComponentName)); + } + if (model.Cost <= 0) + { + throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost)); + } + _logger.LogInformation("Component. ComponentName:{ComponentName}.Cost:{ Cost}. Id: { Id}", model.ComponentName, model.Cost, model.Id); + var element = _componentStorage.GetElement(new ComponentSearchModel + { + ComponentName = model.ComponentName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Компонент с таким названием уже есть"); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs new file mode 100644 index 0000000..c96ad04 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -0,0 +1,188 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для заказов + /// + public class OrderLogic : IOrderLogic + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем заказов + /// + private readonly IOrderStorage _orderStorage; + + /// + /// Конструктор + /// + /// + /// + public OrderLogic(ILogger logger, IOrderStorage +orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } + + /// + /// Получение списка + /// + /// + /// + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. Order.Id:{ 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 bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) + { + _logger.LogWarning("Insert operation failed. Order status incorrect."); + return false; + } + + model.Status = OrderStatus.Принят; + + if (_orderStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + /// + /// Смена статуса заказа (Выполняется) + /// + /// + /// + public bool TakeOrderInWork(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } + + /// + /// Смена статуса заказа (Выдан) + /// + /// + /// + public bool FinishOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выдан); + } + + /// + /// Смена статуса заказа (Готов) + /// + /// + /// + public bool DeliveryOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Готов); + } + + /// + /// Проверка модели заказа + /// + /// + /// + private void CheckModel(OrderBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (model.PlaneId < 0) + { + throw new ArgumentNullException("Некорректный идентификатор изделия", nameof(model.PlaneId)); + } + if (model.Count <= 0) + { + throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); + } + if (model.Sum <= 0) + { + throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); + } + _logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. PlaneId: { PlaneId}", model.Id, model.Sum, model.PlaneId); + } + + /// + /// Смена статуса заказа + /// + /// + /// + /// + private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) + { + var element = _orderStorage.GetElement(new OrderSearchModel + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (element.Status + 1 != newStatus) + { + _logger.LogWarning("Change status operation failed"); + return false; + } + + model.Status = newStatus; + + if (model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = element.DateImplement; + } + CheckModel(model, false); + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Change status operation failed"); + return false; + } + return true; + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs new file mode 100644 index 0000000..82de87f --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs @@ -0,0 +1,174 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для изделия + /// + public class PlaneLogic : IPlaneLogic + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем изделий + /// + private readonly IPlaneStorage _planeStorage; + + /// + /// Конструктор + /// + /// + /// + public PlaneLogic(ILogger logger, IPlaneStorage +planeStorage) + { + _logger = logger; + _planeStorage = planeStorage; + } + + /// + /// Получение списка + /// + /// + /// + public List? ReadList(PlaneSearchModel? model) + { + _logger.LogInformation("ReadList. PlaneName:{PlaneName}.Id:{ Id}", model?.PlaneName, model?.Id); + + var list = model == null ? _planeStorage.GetFullList() : _planeStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + /// + /// Получение отдельной записи + /// + /// + /// + /// + public PlaneViewModel? ReadElement(PlaneSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. PlaneName:{PlaneName}.Id:{ Id}", model.PlaneName, model.Id); + + var element = _planeStorage.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(PlaneBindingModel model) + { + CheckModel(model); + + if (_planeStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + /// + /// Изменение записи + /// + /// + /// + public bool Update(PlaneBindingModel model) + { + CheckModel(model); + + if (_planeStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + /// + /// Удаление записи + /// + /// + /// + public bool Delete(PlaneBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_planeStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + /// + /// Проверка модели изделия + /// + /// + /// + private void CheckModel(PlaneBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.PlaneName)) + { + throw new ArgumentNullException("Нет названия изделия", nameof(model.PlaneName)); + } + if (model.Price <= 0) + { + throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price)); + } + _logger.LogInformation("Plane. PlaneName:{PlaneName}.Price:{ Price}. Id: { Id}", model.PlaneName, model.Price, model.Id); + var element = _planeStorage.GetElement(new PlaneSearchModel + { + PlaneName = model.PlaneName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Изделие с таким названием уже есть"); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/AircraftPlantContracts.csproj b/AircraftPlant/AircraftPlantContracts/AircraftPlantContracts.csproj new file mode 100644 index 0000000..cf0ac69 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/AircraftPlantContracts.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/ComponentBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/ComponentBindingModel.cs new file mode 100644 index 0000000..2315e3f --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/ComponentBindingModel.cs @@ -0,0 +1,31 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для сохранения данных для компонентов + /// + public class ComponentBindingModel : IComponentModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название компонента + /// + public string ComponentName { get; set; } = string.Empty; + + /// + /// Стоимость компонента + /// + public double Cost { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/OrderBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/OrderBindingModel.cs new file mode 100644 index 0000000..8d4a12b --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/OrderBindingModel.cs @@ -0,0 +1,52 @@ +using AircraftPlantDataModels.Enums; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для сохранения данных для заказов + /// + public class OrderBindingModel : IOrderModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Идентификатор изделия + /// + public int PlaneId { get; set; } + + /// + /// Количество изделий + /// + public int Count { get; set; } + + /// + /// Сумма заказа + /// + public double Sum { get; set; } + + /// + /// Статус заказа + /// + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + /// + /// Дата создания заказа + /// + public DateTime DateCreate { get; set; } = DateTime.Now; + + /// + /// Дата выполнения заказа + /// + public DateTime? DateImplement { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/PlaneBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/PlaneBindingModel.cs new file mode 100644 index 0000000..ca69baf --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/PlaneBindingModel.cs @@ -0,0 +1,40 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для сохранения данных для изделий + /// + public class PlaneBindingModel : IPlaneModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название изделия + /// + public string PlaneName { get; set; } = string.Empty; + + /// + /// Стоимость изделия + /// + public double Price { get; set; } + + /// + /// Коллекция компонентов изделия + /// + public Dictionary PlaneComponents + { + get; + set; + } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IComponentLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IComponentLogic.cs new file mode 100644 index 0000000..973aa2a --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IComponentLogic.cs @@ -0,0 +1,52 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BusinessLogicsContracts +{ + /// + /// Интерфейс для описания работы бизнес-логики для компонентов + /// + public interface IComponentLogic + { + /// + /// Получение списка + /// + /// + /// + List? ReadList(ComponentSearchModel? model); + + /// + /// Получение отдельной записи + /// + /// + /// + ComponentViewModel? ReadElement(ComponentSearchModel model); + + /// + /// Создание записи + /// + /// + /// + bool Create(ComponentBindingModel model); + + /// + /// Изменение записи + /// + /// + /// + bool Update(ComponentBindingModel model); + + /// + /// Удаление записи + /// + /// + /// + bool Delete(ComponentBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IOrderLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IOrderLogic.cs new file mode 100644 index 0000000..a329126 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -0,0 +1,52 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BusinessLogicsContracts +{ + /// + /// Интерфейс для описания работы бизнес-логики для заказов + /// + public interface IOrderLogic + { + /// + /// Получение списка + /// + /// + /// + List? ReadList(OrderSearchModel? model); + + /// + /// Создание заказа + /// + /// + /// + bool CreateOrder(OrderBindingModel model); + + /// + /// Смена статуса заказа (Выполняется) + /// + /// + /// + bool TakeOrderInWork(OrderBindingModel model); + + /// + /// Смена статуса заказа (Выдан) + /// + /// + /// + bool FinishOrder(OrderBindingModel model); + + /// + /// Смена статуса заказа (Готов) + /// + /// + /// + bool DeliveryOrder(OrderBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IPlaneLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IPlaneLogic.cs new file mode 100644 index 0000000..0ffe21a --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IPlaneLogic.cs @@ -0,0 +1,52 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BusinessLogicsContracts +{ + /// + /// Интерфейс для описания работы бизнес-логики для изделий + /// + public interface IPlaneLogic + { + /// + /// Получение списка + /// + /// + /// + List? ReadList(PlaneSearchModel? model); + + /// + /// Получение отдельной записи + /// + /// + /// + PlaneViewModel? ReadElement(PlaneSearchModel model); + + /// + /// Создание записи + /// + /// + /// + bool Create(PlaneBindingModel model); + + /// + /// Изменение записи + /// + /// + /// + bool Update(PlaneBindingModel model); + + /// + /// Удаление записи + /// + /// + /// + bool Delete(PlaneBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/ComponentSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/ComponentSearchModel.cs new file mode 100644 index 0000000..db83bd8 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/ComponentSearchModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.SearchModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для поиска данных для компонентов + /// + public class ComponentSearchModel + { + /// + /// Идентификатор + /// + public int? Id { get; set; } + + /// + /// Название компонента + /// + public string? ComponentName { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs new file mode 100644 index 0000000..3ff9399 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.SearchModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для поиска данных для заказов + /// + public class OrderSearchModel + { + /// + /// Идентификатор + /// + public int? Id { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/PlaneSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/PlaneSearchModel.cs new file mode 100644 index 0000000..5950036 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/PlaneSearchModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.SearchModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для поиска данных для изделий + /// + public class PlaneSearchModel + { + /// + /// Идентификатор + /// + public int? Id { get; set; } + + /// + /// Название изделия + /// + public string? PlaneName { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IComponentStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IComponentStorage.cs new file mode 100644 index 0000000..ea4f0ce --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IComponentStorage.cs @@ -0,0 +1,58 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.StoragesContracts +{ + /// + /// Интерфейс для описания работы с хранилищем для компонентов + /// + public interface IComponentStorage + { + /// + /// Получение полного списка + /// + /// + List GetFullList(); + + /// + /// Получение фильтрованного списка + /// + /// + /// + List GetFilteredList(ComponentSearchModel model); + + /// + /// Получение элемента + /// + /// + /// + ComponentViewModel? GetElement(ComponentSearchModel model); + + /// + /// Добавление элемента + /// + /// + /// + ComponentViewModel? Insert(ComponentBindingModel model); + + /// + /// Редактирование элемента + /// + /// + /// + ComponentViewModel? Update(ComponentBindingModel model); + + /// + /// Удаление элемента + /// + /// + /// + ComponentViewModel? Delete(ComponentBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IOrderStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IOrderStorage.cs new file mode 100644 index 0000000..01050c4 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IOrderStorage.cs @@ -0,0 +1,58 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.StoragesContracts +{ + /// + /// Интерфейс для описания работы с хранилищем для заказов + /// + public interface IOrderStorage + { + /// + /// Получение полного списка + /// + /// + List GetFullList(); + + /// + /// Получение фильтрованного списка + /// + /// + /// + List GetFilteredList(OrderSearchModel model); + + /// + /// Получение элемента + /// + /// + /// + OrderViewModel? GetElement(OrderSearchModel model); + + /// + /// Добавление элемента + /// + /// + /// + OrderViewModel? Insert(OrderBindingModel model); + + /// + /// Редактирование элемента + /// + /// + /// + OrderViewModel? Update(OrderBindingModel model); + + /// + /// Удаление элемента + /// + /// + /// + OrderViewModel? Delete(OrderBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IPlaneStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IPlaneStorage.cs new file mode 100644 index 0000000..e4a8ed1 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IPlaneStorage.cs @@ -0,0 +1,58 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.StoragesContracts +{ + /// + /// Интерфейс для описания работы с хранилищем для изделий + /// + public interface IPlaneStorage + { + /// + /// Получение полного списка + /// + /// + List GetFullList(); + + /// + /// Получение фильтрованного списка + /// + /// + /// + List GetFilteredList(PlaneSearchModel model); + + /// + /// Получение элемента + /// + /// + /// + PlaneViewModel? GetElement(PlaneSearchModel model); + + /// + /// Добавление элемента + /// + /// + /// + PlaneViewModel? Insert(PlaneBindingModel model); + + /// + /// Редактирование элемента + /// + /// + /// + PlaneViewModel? Update(PlaneBindingModel model); + + /// + /// Удаление элемента + /// + /// + /// + PlaneViewModel? Delete(PlaneBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ComponentViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ComponentViewModel.cs new file mode 100644 index 0000000..9eb4c3e --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ComponentViewModel.cs @@ -0,0 +1,34 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для передачи данных пользователю + /// для отображения для компонентов + /// + public class ComponentViewModel : IComponentModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название компонента + /// + [DisplayName("Название компонента")] + public string ComponentName { get; set; } = string.Empty; + + /// + /// Стоимость компонента + /// + [DisplayName("Цена")] + public double Cost { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/OrderViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/OrderViewModel.cs new file mode 100644 index 0000000..6b4c301 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/OrderViewModel.cs @@ -0,0 +1,65 @@ +using AircraftPlantDataModels.Enums; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для передачи данных пользователю + /// для отображения для заказов + /// + public class OrderViewModel : IOrderModel + { + /// + /// Идентификатор + /// + [DisplayName("Номер")] + public int Id { get; set; } + + /// + /// Идентификатор изделия + /// + public int PlaneId { get; set; } + + /// + /// Название изделия + /// + [DisplayName("Изделие")] + public string PlaneName { get; set; } = string.Empty; + + /// + /// Количество изделий + /// + [DisplayName("Количество")] + public int Count { get; set; } + + /// + /// Сумма заказа + /// + [DisplayName("Сумма")] + public double Sum { get; set; } + + /// + /// Статус заказа + /// + [DisplayName("Статус")] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + /// + /// Дата создания заказа + /// + [DisplayName("Дата создания")] + public DateTime DateCreate { get; set; } = DateTime.Now; + + /// + /// Дата выполнения заказа + /// + [DisplayName("Дата выполнения")] + public DateTime? DateImplement { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/PlaneViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/PlaneViewModel.cs new file mode 100644 index 0000000..0e60ba4 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/PlaneViewModel.cs @@ -0,0 +1,43 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для передачи данных пользователю + /// для отображения для изделий + /// + public class PlaneViewModel : IPlaneModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название изделия + /// + [DisplayName("Название изделия")] + public string PlaneName { get; set; } = string.Empty; + + /// + /// Стоимость изделия + /// + [DisplayName("Цена")] + public double Price { get; set; } + + /// + /// Коллекция компонентов изделия + /// + public Dictionary PlaneComponents + { + get; + set; + } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/AircraftPlantDataModels.csproj b/AircraftPlant/AircraftPlantDataModels/AircraftPlantDataModels.csproj new file mode 100644 index 0000000..132c02c --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/AircraftPlantDataModels.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + diff --git a/AircraftPlant/AircraftPlantDataModels/Enums/OrderStatus.cs b/AircraftPlant/AircraftPlantDataModels/Enums/OrderStatus.cs new file mode 100644 index 0000000..ac2308f --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Enums/OrderStatus.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Enums +{ + /// + /// Статус заказа + /// + public enum OrderStatus + { + Неизвестен = -1, + + Принят = 0, + + Выполняется = 1, + + Готов = 2, + + Выдан = 3 + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IComponentModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IComponentModel.cs new file mode 100644 index 0000000..6b1ba06 --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IComponentModel.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Models +{ + /// + /// Интерфейс для модели компонента + /// + public interface IComponentModel : IId + { + /// + /// Имя компонента + /// + string ComponentName { get; } + + /// + /// Стоимость компонента + /// + double Cost { get; } + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IId.cs b/AircraftPlant/AircraftPlantDataModels/Models/IId.cs new file mode 100644 index 0000000..aece502 --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IId.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Models +{ + /// + /// Интерфейс для идентификатора + /// + public interface IId + { + /// + /// Идентификатор + /// + int Id { get; } + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IOrderModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IOrderModel.cs new file mode 100644 index 0000000..f65aeb7 --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IOrderModel.cs @@ -0,0 +1,45 @@ +using AircraftPlantDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Models +{ + /// + /// Интерфейс для модели заказа + /// + public interface IOrderModel : IId + { + /// + /// Идентификатор изделия + /// + int PlaneId { get; } + + /// + /// Количество изделий + /// + int Count { get; } + + /// + /// Сумма заказа + /// + double Sum { get; } + + /// + /// Статус заказа + /// + OrderStatus Status { get; } + + /// + /// Дата создания заказа + /// + DateTime DateCreate { get; } + + /// + /// Дата выполнения заказа + /// + DateTime? DateImplement { get; } + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IPlaneModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IPlaneModel.cs new file mode 100644 index 0000000..b8d54fc --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IPlaneModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Models +{ + /// + /// Интерфейс для модели изделия + /// + public interface IPlaneModel : IId + { + /// + /// Название изделия + /// + string PlaneName { get; } + + /// + /// Стоимость изделия + /// + double Price { get; } + + /// + /// Коллекция компонентов изделия + /// + Dictionary PlaneComponents { get; } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/AircraftPlantListImplement.csproj b/AircraftPlant/AircraftPlantListImplement/AircraftPlantListImplement.csproj new file mode 100644 index 0000000..229b307 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/AircraftPlantListImplement.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs new file mode 100644 index 0000000..eb745b4 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs @@ -0,0 +1,58 @@ +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement +{ + /// + /// Класс для хранения списков классов-моделей (паттерн Singleton) + /// + public class DataListSingleton + { + /// + /// Ссылка на класс + /// + private static DataListSingleton? _instance; + + /// + /// Список классов-моделей компонентов + /// + public List Components { get; set; } + + /// + /// Список классов-моделей заказов + /// + public List Orders { get; set; } + + /// + /// Список классов-моделей изделий + /// + public List Planes { get; set; } + + /// + /// Конструктор + /// + private DataListSingleton() + { + Components = new List(); + Orders = new List(); + Planes = new List(); + } + + /// + /// Получить ссылку на класс + /// + /// + public static DataListSingleton GetInstance() + { + if (_instance == null) + { + _instance = new DataListSingleton(); + } + return _instance; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/ComponentStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/ComponentStorage.cs new file mode 100644 index 0000000..4dfbc8c --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Implements/ComponentStorage.cs @@ -0,0 +1,155 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для компонентов + /// + public class ComponentStorage : IComponentStorage + { + /// + /// Хранилище + /// + private readonly DataListSingleton _source; + + /// + /// Конструктор + /// + public ComponentStorage() + { + _source = DataListSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + var result = new List(); + foreach (var component in _source.Components) + { + result.Add(component.GetViewModel); + } + return result; + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(ComponentSearchModel model) + { + var result = new List(); + + if (string.IsNullOrEmpty(model.ComponentName)) + { + return result; + } + + foreach (var component in _source.Components) + { + if (component.ComponentName.Contains(model.ComponentName)) + { + result.Add(component.GetViewModel); + } + } + return result; + } + + /// + /// Получение элемента + /// + /// + /// + public ComponentViewModel? GetElement(ComponentSearchModel model) + { + if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) + { + return null; + } + + foreach (var component in _source.Components) + { + if ((!string.IsNullOrEmpty(model.ComponentName) && component.ComponentName == model.ComponentName) || (model.Id.HasValue && component.Id == model.Id)) + { + return component.GetViewModel; + } + } + return null; + } + + /// + /// Добавление элемента + /// + /// + /// + public ComponentViewModel? Insert(ComponentBindingModel model) + { + model.Id = 1; + foreach (var component in _source.Components) + { + if (model.Id <= component.Id) + { + model.Id = component.Id + 1; + } + } + + var newComponent = Component.Create(model); + if (newComponent == null) + { + return null; + } + + _source.Components.Add(newComponent); + return newComponent.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public ComponentViewModel? Update(ComponentBindingModel model) + { + foreach (var component in _source.Components) + { + if (component.Id == model.Id) + { + component.Update(model); + return component.GetViewModel; + } + } + return null; + } + + /// + /// Удаление элемента + /// + /// + /// + public ComponentViewModel? Delete(ComponentBindingModel model) + { + for (int i = 0; i < _source.Components.Count; ++i) + { + if (_source.Components[i].Id == model.Id) + { + var element = _source.Components[i]; + _source.Components.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs new file mode 100644 index 0000000..f24a094 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs @@ -0,0 +1,154 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для заказов + /// + public class OrderStorage : IOrderStorage + { + /// + /// Хранилище + /// + private readonly DataListSingleton _source; + + /// + /// Конструктор + /// + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + var result = new List(); + foreach (var order in _source.Orders) + { + result.Add(order.GetViewModel); + } + return result; + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(OrderSearchModel model) + { + var result = new List(); + if (!model.Id.HasValue) + { + return result; + } + + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + result.Add(order.GetViewModel); + } + } + return result; + } + + /// + /// Получение элемента + /// + /// + /// + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + return order.GetViewModel; + } + } + return null; + } + + /// + /// Добавление элемента + /// + /// + /// + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = 1; + foreach (var order in _source.Orders) + { + if (model.Id <= order.Id) + { + model.Id = order.Id + 1; + } + } + + var newOrder = Order.Create(model); + if (newOrder == null) + { + return null; + } + + _source.Orders.Add(newOrder); + return newOrder.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); + return order.GetViewModel; + } + } + return null; + } + + /// + /// Удаление элемента + /// + /// + /// + public OrderViewModel? Delete(OrderBindingModel model) + { + for (int i = 0; i < _source.Orders.Count; ++i) + { + if (_source.Orders[i].Id == model.Id) + { + var element = _source.Orders[i]; + _source.Orders.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/PlaneStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/PlaneStorage.cs new file mode 100644 index 0000000..62f2c58 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Implements/PlaneStorage.cs @@ -0,0 +1,154 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для изделий + /// + public class PlaneStorage : IPlaneStorage + { + /// + /// Хранилище + /// + private readonly DataListSingleton _source; + + /// + /// Конструктор + /// + public PlaneStorage() + { + _source = DataListSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + var result = new List(); + foreach (var plane in _source.Planes) + { + result.Add(plane.GetViewModel); + } + return result; + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(PlaneSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.PlaneName)) + { + return result; + } + + foreach (var plane in _source.Planes) + { + if (plane.PlaneName.Contains(model.PlaneName)) + { + result.Add(plane.GetViewModel); + } + } + return result; + } + + /// + /// Получение элемента + /// + /// + /// + public PlaneViewModel? GetElement(PlaneSearchModel model) + { + if (string.IsNullOrEmpty(model.PlaneName) && !model.Id.HasValue) + { + return null; + } + + foreach (var plane in _source.Planes) + { + if ((!string.IsNullOrEmpty(model.PlaneName) && plane.PlaneName == model.PlaneName) || (model.Id.HasValue && plane.Id == model.Id)) + { + return plane.GetViewModel; + } + } + return null; + } + + /// + /// Добавление элемента + /// + /// + /// + public PlaneViewModel? Insert(PlaneBindingModel model) + { + model.Id = 1; + foreach (var plane in _source.Planes) + { + if (model.Id <= plane.Id) + { + model.Id = plane.Id + 1; + } + } + + var newPlane = Plane.Create(model); + if (newPlane == null) + { + return null; + } + + _source.Planes.Add(newPlane); + return newPlane.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public PlaneViewModel? Update(PlaneBindingModel model) + { + foreach (var plane in _source.Planes) + { + if (plane.Id == model.Id) + { + plane.Update(model); + return plane.GetViewModel; + } + } + return null; + } + + /// + /// Удаление элемента + /// + /// + /// + public PlaneViewModel? Delete(PlaneBindingModel model) + { + for (int i = 0; i < _source.Planes.Count; ++i) + { + if (_source.Planes[i].Id == model.Id) + { + var element = _source.Planes[i]; + _source.Planes.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Component.cs b/AircraftPlant/AircraftPlantListImplement/Models/Component.cs new file mode 100644 index 0000000..715f6fd --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Models/Component.cs @@ -0,0 +1,77 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Models +{ + /// + /// Сущность "Компонент" + /// + public class Component : IComponentModel + { + /// + /// Идентификатор + /// + public int Id { get; private set; } + + /// + /// Название компонента + /// + public string ComponentName { get; private set; } = string.Empty; + + /// + /// Стоимость компонента + /// + public double Cost { get; set; } + + /// + /// Создание модели компонента + /// + /// + /// + public static Component? Create(ComponentBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Component() + { + Id = model.Id, + ComponentName = model.ComponentName, + Cost = model.Cost + }; + } + + /// + /// Изменение модели компонента + /// + /// + public void Update(ComponentBindingModel? model) + { + if (model == null) + { + return; + } + + ComponentName = model.ComponentName; + Cost = model.Cost; + } + + /// + /// Получение модели компонента + /// + public ComponentViewModel GetViewModel => new() + { + Id = Id, + ComponentName = ComponentName, + Cost = Cost + }; + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Order.cs b/AircraftPlant/AircraftPlantListImplement/Models/Order.cs new file mode 100644 index 0000000..d85fdb5 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Models/Order.cs @@ -0,0 +1,106 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Enums; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Models +{ + /// + /// Сущность "Заказ" + /// + public class Order : IOrderModel + { + /// + /// Идентификатор + /// + public int Id { get; private set; } + + /// + /// Идентификатор изделия + /// + public int PlaneId { get; private set; } + + /// + /// Количество изделий + /// + public int Count { get; private set; } + + /// + /// Сумма заказа + /// + public double Sum { get; private set; } + + /// + /// Статус заказа + /// + public OrderStatus Status { get; private set; } + + /// + /// Дата создания заказа + /// + public DateTime DateCreate { get; private set; } + + /// + /// Дата выполнения заказа + /// + public DateTime? DateImplement { get; private set; } + + /// + /// Создание модели заказа + /// + /// + /// + public static Order? Create(OrderBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Order + { + Id = model.Id, + PlaneId = model.PlaneId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } + + /// + /// Изменение модели заказа + /// + /// + public void Update(OrderBindingModel? model) + { + if (model == null) + { + return; + } + + Status = model.Status; + DateImplement = model.DateImplement; + } + + /// + /// Получение модели заказа + /// + public OrderViewModel GetViewModel => new() + { + Id = Id, + PlaneId = PlaneId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Plane.cs b/AircraftPlant/AircraftPlantListImplement/Models/Plane.cs new file mode 100644 index 0000000..f31183d --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Models/Plane.cs @@ -0,0 +1,90 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Models +{ + /// + /// Сущность "Изделие" + /// + public class Plane : IPlaneModel + { + /// + /// Идентификатор + /// + public int Id { get; private set; } + + /// + /// Название изделия + /// + public string PlaneName { get; private set; } = string.Empty; + + /// + /// Стоимость изделия + /// + public double Price { get; private set; } + + /// + /// Коллекция компонентов изделия + /// + public Dictionary PlaneComponents + { + get; + private set; + } = new Dictionary(); + + /// + /// Создание модели изделия + /// + /// + /// + public static Plane? Create(PlaneBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Plane() + { + Id = model.Id, + PlaneName = model.PlaneName, + Price = model.Price, + PlaneComponents = model.PlaneComponents + }; + } + + /// + /// Изменение модели изделия + /// + /// + public void Update(PlaneBindingModel? model) + { + if (model == null) + { + return; + } + + PlaneName = model.PlaneName; + Price = model.Price; + PlaneComponents = model.PlaneComponents; + } + + /// + /// Получение модели изделия + /// + public PlaneViewModel GetViewModel => new() + { + Id = Id, + PlaneName = PlaneName, + Price = Price, + PlaneComponents = PlaneComponents + }; + } +} diff --git a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj index b57c89e..ae15140 100644 --- a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj +++ b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj @@ -8,4 +8,26 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/Form1.Designer.cs b/AircraftPlant/AircraftPlantView/Form1.Designer.cs deleted file mode 100644 index 33faa03..0000000 --- a/AircraftPlant/AircraftPlantView/Form1.Designer.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace AircraftPlantView -{ - 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 - } -} diff --git a/AircraftPlant/AircraftPlantView/Form1.cs b/AircraftPlant/AircraftPlantView/Form1.cs deleted file mode 100644 index 5073102..0000000 --- a/AircraftPlant/AircraftPlantView/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AircraftPlantView -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} diff --git a/AircraftPlant/AircraftPlantView/FormComponent.Designer.cs b/AircraftPlant/AircraftPlantView/FormComponent.Designer.cs new file mode 100644 index 0000000..aafa5ae --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormComponent.Designer.cs @@ -0,0 +1,118 @@ +namespace AircraftPlantView +{ + partial class FormComponent + { + /// + /// 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() + { + buttonCancel = new Button(); + buttonSave = new Button(); + labelComponentName = new Label(); + labelComponentCost = new Label(); + textBoxComponentName = new TextBox(); + textBoxComponentCost = new TextBox(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 76); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 0; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(216, 76); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 1; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // labelComponentName + // + labelComponentName.AutoSize = true; + labelComponentName.Location = new Point(12, 15); + labelComponentName.Name = "labelComponentName"; + labelComponentName.Size = new Size(62, 15); + labelComponentName.TabIndex = 2; + labelComponentName.Text = "Название:"; + // + // labelComponentCost + // + labelComponentCost.AutoSize = true; + labelComponentCost.Location = new Point(12, 44); + labelComponentCost.Name = "labelComponentCost"; + labelComponentCost.Size = new Size(38, 15); + labelComponentCost.TabIndex = 3; + labelComponentCost.Text = "Цена:"; + // + // textBoxComponentName + // + textBoxComponentName.Location = new Point(80, 12); + textBoxComponentName.Name = "textBoxComponentName"; + textBoxComponentName.Size = new Size(292, 23); + textBoxComponentName.TabIndex = 4; + // + // textBoxComponentCost + // + textBoxComponentCost.Location = new Point(80, 41); + textBoxComponentCost.Name = "textBoxComponentCost"; + textBoxComponentCost.Size = new Size(292, 23); + textBoxComponentCost.TabIndex = 5; + // + // FormComponent + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 111); + Controls.Add(textBoxComponentCost); + Controls.Add(textBoxComponentName); + Controls.Add(labelComponentCost); + Controls.Add(labelComponentName); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Name = "FormComponent"; + Text = "Компонент"; + Load += FormComponent_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSave; + private Label labelComponentName; + private Label labelComponentCost; + private TextBox textBoxComponentName; + private TextBox textBoxComponentCost; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormComponent.cs b/AircraftPlant/AircraftPlantView/FormComponent.cs new file mode 100644 index 0000000..bcccce2 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormComponent.cs @@ -0,0 +1,136 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using Microsoft.Extensions.Logging; +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 AircraftPlantView +{ + /// + /// Форма для работы с компонентами + /// + public partial class FormComponent : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для компонента + /// + private readonly IComponentLogic _logic; + + /// + /// Идентификатор + /// + private int? _id; + public int Id { set { _id = value; } } + + /// + /// Конструктор + /// + /// + /// + public FormComponent(ILogger logger, IComponentLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка информации о компоненте + /// + /// + /// + private void FormComponent_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение компонента"); + var view = _logic.ReadElement(new ComponentSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxComponentName.Text = view.ComponentName; + textBoxComponentCost.Text = view.Cost.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxComponentName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxComponentCost.Text)) + { + MessageBox.Show("Заполните стоимость", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _logger.LogInformation("Сохранение компонента"); + try + { + var model = new ComponentBindingModel + { + Id = _id ?? 0, + ComponentName = textBoxComponentName.Text, + Cost = Convert.ToDouble(textBoxComponentCost.Text) + }; + + 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, "Ошибка сохранения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/AircraftPlant/AircraftPlantView/Form1.resx b/AircraftPlant/AircraftPlantView/FormComponent.resx similarity index 93% rename from AircraftPlant/AircraftPlantView/Form1.resx rename to AircraftPlant/AircraftPlantView/FormComponent.resx index 1af7de1..af32865 100644 --- a/AircraftPlant/AircraftPlantView/Form1.resx +++ b/AircraftPlant/AircraftPlantView/FormComponent.resx @@ -1,17 +1,17 @@  - diff --git a/AircraftPlant/AircraftPlantView/FormComponents.Designer.cs b/AircraftPlant/AircraftPlantView/FormComponents.Designer.cs new file mode 100644 index 0000000..8e8ae7b --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormComponents.Designer.cs @@ -0,0 +1,122 @@ +namespace AircraftPlantView +{ + partial class FormComponents + { + /// + /// 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(); + buttonDelete = new Button(); + buttonRefresh = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(0, 0); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(450, 361); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(480, 15); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(75, 23); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(480, 44); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(75, 23); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(480, 73); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(75, 23); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(480, 102); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(75, 23); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // FormComponents + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormComponents"; + Text = "Компоненты"; + Load += FormComponents_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonDelete; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormComponents.cs b/AircraftPlant/AircraftPlantView/FormComponents.cs new file mode 100644 index 0000000..aa9143b --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormComponents.cs @@ -0,0 +1,154 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +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 AircraftPlantView +{ + /// + /// Форма для вывода всех компонентов + /// + public partial class FormComponents : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для компонента + /// + private readonly IComponentLogic _logic; + + /// + /// Конструктор + /// + /// + /// + public FormComponents(ILogger logger, IComponentLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка списка компонентов + /// + /// + /// + private void FormComponents_Load(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Кнопка "Добавить" + /// + /// + /// + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); + if (service is FormComponent 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(FormComponent)); + if (service is FormComponent form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + 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 ComponentBindingModel { Id = id })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + /// + /// Кнопка "Обновить" + /// + /// + /// + private void buttonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Метод загрузки списка компонентов + /// + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка компонентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormComponents.resx b/AircraftPlant/AircraftPlantView/FormComponents.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormComponents.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/AircraftPlant/AircraftPlantView/FormCreateOrder.Designer.cs b/AircraftPlant/AircraftPlantView/FormCreateOrder.Designer.cs new file mode 100644 index 0000000..9ebc099 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormCreateOrder.Designer.cs @@ -0,0 +1,144 @@ +namespace AircraftPlantView +{ + partial class FormCreateOrder + { + /// + /// 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() + { + comboBoxPlane = new ComboBox(); + textBoxCount = new TextBox(); + textBoxSum = new TextBox(); + labelPlane = new Label(); + labelCount = new Label(); + labelSum = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + SuspendLayout(); + // + // comboBoxPlane + // + comboBoxPlane.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxPlane.FormattingEnabled = true; + comboBoxPlane.Location = new Point(90, 12); + comboBoxPlane.Name = "comboBoxPlane"; + comboBoxPlane.Size = new Size(282, 23); + comboBoxPlane.TabIndex = 0; + comboBoxPlane.SelectedIndexChanged += comboBoxPlane_SelectedIndexChanged; + // + // textBoxCount + // + textBoxCount.Location = new Point(90, 41); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(282, 23); + textBoxCount.TabIndex = 1; + textBoxCount.TextChanged += textBoxCount_TextChanged; + // + // textBoxSum + // + textBoxSum.Location = new Point(90, 70); + textBoxSum.Name = "textBoxSum"; + textBoxSum.Size = new Size(282, 23); + textBoxSum.TabIndex = 2; + // + // labelPlane + // + labelPlane.AutoSize = true; + labelPlane.Location = new Point(12, 15); + labelPlane.Name = "labelPlane"; + labelPlane.Size = new Size(56, 15); + labelPlane.TabIndex = 3; + labelPlane.Text = "Изделие:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(12, 44); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(75, 15); + labelCount.TabIndex = 4; + labelCount.Text = "Количество:"; + // + // labelSum + // + labelSum.AutoSize = true; + labelSum.Location = new Point(12, 73); + labelSum.Name = "labelSum"; + labelSum.Size = new Size(48, 15); + labelSum.TabIndex = 5; + labelSum.Text = "Сумма:"; + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 99); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 6; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(216, 99); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 7; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // FormCreateOrder + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 131); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(labelSum); + Controls.Add(labelCount); + Controls.Add(labelPlane); + Controls.Add(textBoxSum); + Controls.Add(textBoxCount); + Controls.Add(comboBoxPlane); + Name = "FormCreateOrder"; + Text = "Заказ"; + Load += FormCreateOrder_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxPlane; + private TextBox textBoxCount; + private TextBox textBoxSum; + private Label labelPlane; + private Label labelCount; + private Label labelSum; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormCreateOrder.cs b/AircraftPlant/AircraftPlantView/FormCreateOrder.cs new file mode 100644 index 0000000..77c1baf --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormCreateOrder.cs @@ -0,0 +1,171 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using Microsoft.Extensions.Logging; +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 AircraftPlantView +{ + public partial class FormCreateOrder : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для изделий + /// + private readonly IPlaneLogic _logicP; + + /// + /// Бизнес-логика для заказов + /// + private readonly IOrderLogic _logicO; + + /// + /// Конструктор + /// + /// + /// + /// + public FormCreateOrder(ILogger logger, IPlaneLogic logicP, IOrderLogic logicO) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicO = logicO; + } + + /// + /// Загрузка списка изделий для заказа + /// + /// + /// + private void FormCreateOrder_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий для заказа"); + try + { + var list = _logicP.ReadList(null); + if (list != null) + { + comboBoxPlane.DisplayMember = "PlaneName"; + comboBoxPlane.ValueMember = "Id"; + comboBoxPlane.DataSource = list; + comboBoxPlane.SelectedItem = null; + } + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Изменение поля "Количество" + /// + /// + /// + private void textBoxCount_TextChanged(object sender, EventArgs e) + { + CalcSum(); + } + + /// + /// Изменение значения в выпадающем списке + /// + /// + /// + private void comboBoxPlane_SelectedIndexChanged(object sender, EventArgs e) + { + CalcSum(); + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxPlane.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание заказа"); + try + { + var operationResult = _logicO.CreateOrder(new OrderBindingModel + { + PlaneId = Convert.ToInt32(comboBoxPlane.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text), + Sum = Convert.ToDouble(textBoxSum.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + /// + /// Подсчет суммы заказа + /// + private void CalcSum() + { + if (comboBoxPlane.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) + { + try + { + int id = Convert.ToInt32(comboBoxPlane.SelectedValue); + var product = _logicP.ReadElement(new PlaneSearchModel { Id = id }); + int count = Convert.ToInt32(textBoxCount.Text); + textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString(); + _logger.LogInformation("Расчет суммы заказа"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка расчета суммы заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormCreateOrder.resx b/AircraftPlant/AircraftPlantView/FormCreateOrder.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormCreateOrder.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/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs new file mode 100644 index 0000000..a68fe27 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -0,0 +1,179 @@ +namespace AircraftPlantView +{ + 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); + } + + #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(); + buttonCreateOrder = new Button(); + buttonTakeOrderInWork = new Button(); + buttonOrderReady = new Button(); + buttonIssuedOrder = new Button(); + buttonRefresh = new Button(); + menuStrip = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem = new ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + menuStrip.SuspendLayout(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(0, 24); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(800, 337); + dataGridView.TabIndex = 0; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(822, 36); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(150, 23); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += buttonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Location = new Point(822, 76); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(150, 23); + buttonTakeOrderInWork.TabIndex = 2; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = true; + buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Location = new Point(822, 105); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(150, 23); + buttonOrderReady.TabIndex = 3; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = true; + buttonOrderReady.Click += buttonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(822, 134); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(150, 23); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += buttonIssuedOrder_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(822, 172); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(150, 23); + buttonRefresh.TabIndex = 5; + buttonRefresh.Text = "Обновить список"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(984, 24); + menuStrip.TabIndex = 6; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(94, 20); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компоненты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; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(984, 361); + Controls.Add(buttonRefresh); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Name = "FormMain"; + Text = "Авиационный завод"; + Load += FormMain_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonIssuedOrder; + private Button buttonRefresh; + private MenuStrip menuStrip; + private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem компонентыToolStripMenuItem; + private ToolStripMenuItem изделияToolStripMenuItem; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs new file mode 100644 index 0000000..39a70bc --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -0,0 +1,216 @@ +using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +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 AircraftPlantView +{ + /// + /// Главная форма + /// + public partial class FormMain : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для заказов + /// + private readonly IOrderLogic _logic; + + /// + /// Конструктор + /// + /// + /// + public FormMain(ILogger logger, IOrderLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка списка заказов + /// + /// + /// + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Показать список всех компонентов + /// + /// + /// + 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(FormPlanes)); + if (service is FormPlanes 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 = _logic.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 = _logic.DeliveryOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Кнопка "Заказ выдан" + /// + /// + /// + private void 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 = _logic.FinishOrder(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 buttonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Метод загрузки списка заказов + /// + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["PlaneName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["PlaneId"].Visible = false; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormMain.resx b/AircraftPlant/AircraftPlantView/FormMain.resx new file mode 100644 index 0000000..6c82d08 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMain.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormPlane.Designer.cs b/AircraftPlant/AircraftPlantView/FormPlane.Designer.cs new file mode 100644 index 0000000..b6a554b --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlane.Designer.cs @@ -0,0 +1,235 @@ +namespace AircraftPlantView +{ + partial class FormPlane + { + /// + /// 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() + { + buttonCancel = new Button(); + buttonSave = new Button(); + textBoxName = new TextBox(); + textBoxPrice = new TextBox(); + labelName = new Label(); + labelPrice = new Label(); + groupBoxComponents = new GroupBox(); + buttonRefresh = new Button(); + buttonDelete = new Button(); + buttonUpdate = new Button(); + buttonAdd = new Button(); + dataGridView = new DataGridView(); + ColumnId = new DataGridViewTextBoxColumn(); + ColumnName = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + groupBoxComponents.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(497, 379); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 0; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(416, 376); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 1; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // textBoxName + // + textBoxName.Location = new Point(90, 12); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(282, 23); + textBoxName.TabIndex = 2; + // + // textBoxPrice + // + textBoxPrice.Enabled = false; + textBoxPrice.Location = new Point(90, 44); + textBoxPrice.Name = "textBoxPrice"; + textBoxPrice.Size = new Size(282, 23); + textBoxPrice.TabIndex = 3; + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(12, 15); + labelName.Name = "labelName"; + labelName.Size = new Size(62, 15); + labelName.TabIndex = 4; + labelName.Text = "Название:"; + // + // labelPrice + // + labelPrice.AutoSize = true; + labelPrice.Location = new Point(12, 44); + labelPrice.Name = "labelPrice"; + labelPrice.Size = new Size(70, 15); + labelPrice.TabIndex = 5; + labelPrice.Text = "Стоимость:"; + // + // groupBoxComponents + // + groupBoxComponents.Controls.Add(buttonRefresh); + groupBoxComponents.Controls.Add(buttonDelete); + groupBoxComponents.Controls.Add(buttonUpdate); + groupBoxComponents.Controls.Add(buttonAdd); + groupBoxComponents.Controls.Add(dataGridView); + groupBoxComponents.Location = new Point(12, 73); + groupBoxComponents.Name = "groupBoxComponents"; + groupBoxComponents.Size = new Size(560, 300); + groupBoxComponents.TabIndex = 6; + groupBoxComponents.TabStop = false; + groupBoxComponents.Text = "Компоненты"; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(450, 109); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(75, 23); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(450, 80); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(75, 23); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(450, 51); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(75, 23); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(450, 22); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(75, 23); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnCount }); + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(3, 19); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(410, 278); + dataGridView.TabIndex = 0; + // + // ColumnId + // + ColumnId.HeaderText = "Id"; + ColumnId.Name = "ColumnId"; + ColumnId.ReadOnly = true; + ColumnId.Visible = false; + // + // ColumnName + // + ColumnName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnName.HeaderText = "Компонент"; + ColumnName.Name = "ColumnName"; + ColumnName.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // FormPlane + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 411); + Controls.Add(groupBoxComponents); + Controls.Add(labelPrice); + Controls.Add(labelName); + Controls.Add(textBoxPrice); + Controls.Add(textBoxName); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Name = "FormPlane"; + Text = "Изделия"; + Load += FormPlane_Load; + groupBoxComponents.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSave; + private TextBox textBoxName; + private TextBox textBoxPrice; + private Label labelName; + private Label labelPrice; + private GroupBox groupBoxComponents; + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonRefresh; + private Button buttonDelete; + private Button buttonUpdate; + private DataGridViewTextBoxColumn ColumnId; + private DataGridViewTextBoxColumn ColumnName; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormPlane.cs b/AircraftPlant/AircraftPlantView/FormPlane.cs new file mode 100644 index 0000000..2edad4b --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlane.cs @@ -0,0 +1,284 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantDataModels.Models; +using Microsoft.Extensions.Logging; +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 AircraftPlantView +{ + /// + /// Форма для изделий + /// + public partial class FormPlane : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для изделий + /// + private readonly IPlaneLogic _logic; + + /// + /// Идентификатор + /// + private int? _id; + public int Id { set { _id = value; } } + + /// + /// Список компонентов изделия + /// + private Dictionary _planeComponents; + + /// + /// Конструктор + /// + /// + /// + public FormPlane(ILogger logger, IPlaneLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _planeComponents = new Dictionary(); + } + + /// + /// Загрузка списка компонентов изделия + /// + /// + /// + private void FormPlane_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка изделия"); + try + { + var view = _logic.ReadElement(new PlaneSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxName.Text = view.PlaneName; + textBoxPrice.Text = view.Price.ToString(); + _planeComponents = view.PlaneComponents ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Кнопка "Добавить" + /// + /// + /// + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormPlaneComponent)); + if (service is FormPlaneComponent form) + { + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); + if (_planeComponents.ContainsKey(form.Id)) + { + _planeComponents[form.Id] = (form.ComponentModel, form.Count); + } + else + { + _planeComponents.Add(form.Id, (form.ComponentModel, form.Count)); + } + LoadData(); + } + } + } + + /// + /// Кнопка "Изменить" + /// + /// + /// + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormPlaneComponent)); + if (service is FormPlaneComponent form) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _planeComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Изменение компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); + _planeComponents[form.Id] = (form.ComponentModel, form.Count); + LoadData(); + } + } + } + } + + /// + /// Кнопка "Удалить" + /// + /// + /// + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + try + { + _logger.LogInformation("Удаление компонента:{ ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _planeComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + } + } + + /// + /// Кнопка "Обновить" + /// + /// + /// + private void buttonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните стоимость", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (_planeComponents == null || _planeComponents.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение изделия"); + try + { + var model = new PlaneBindingModel + { + Id = _id ?? 0, + PlaneName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + PlaneComponents = _planeComponents + }; + 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, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + /// + /// Метод загрузки компонентов изделия + /// + private void LoadData() + { + _logger.LogInformation("Загрузка компонентов изделия"); + try + { + if (_planeComponents != null) + { + dataGridView.Rows.Clear(); + foreach (var pc in _planeComponents) + { + dataGridView.Rows.Add(new object[] + { + pc.Key, + pc.Value.Item1.ComponentName, + pc.Value.Item2 + } + ); + } + textBoxPrice.Text = CalcPrice().ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонентов изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Метод для подсчета стоимости изделия + /// + /// + private double CalcPrice() + { + double price = 0; + foreach (var elem in _planeComponents) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } + return Math.Round(price * 1.1, 2); + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormPlane.resx b/AircraftPlant/AircraftPlantView/FormPlane.resx new file mode 100644 index 0000000..fcacbcb --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlane.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormPlaneComponent.Designer.cs b/AircraftPlant/AircraftPlantView/FormPlaneComponent.Designer.cs new file mode 100644 index 0000000..37941d7 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlaneComponent.Designer.cs @@ -0,0 +1,119 @@ +namespace AircraftPlantView +{ + partial class FormPlaneComponent + { + /// + /// 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() + { + buttonCancel = new Button(); + buttonSave = new Button(); + comboBoxComponent = new ComboBox(); + textBoxCount = new TextBox(); + labelComponent = new Label(); + labelCount = new Label(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 76); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 0; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(216, 76); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 1; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // comboBoxComponent + // + comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxComponent.FormattingEnabled = true; + comboBoxComponent.Location = new Point(90, 12); + comboBoxComponent.Name = "comboBoxComponent"; + comboBoxComponent.Size = new Size(282, 23); + comboBoxComponent.TabIndex = 2; + // + // textBoxCount + // + textBoxCount.Location = new Point(90, 41); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(279, 23); + textBoxCount.TabIndex = 3; + // + // labelComponent + // + labelComponent.AutoSize = true; + labelComponent.Location = new Point(12, 15); + labelComponent.Name = "labelComponent"; + labelComponent.Size = new Size(72, 15); + labelComponent.TabIndex = 4; + labelComponent.Text = "Компонент:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(12, 44); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(75, 15); + labelCount.TabIndex = 5; + labelCount.Text = "Количество:"; + // + // FormPlaneComponent + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 111); + Controls.Add(labelCount); + Controls.Add(labelComponent); + Controls.Add(textBoxCount); + Controls.Add(comboBoxComponent); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Name = "FormPlaneComponent"; + Text = "Компоненты изделия"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSave; + private ComboBox comboBoxComponent; + private TextBox textBoxCount; + private Label labelComponent; + private Label labelCount; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormPlaneComponent.cs b/AircraftPlant/AircraftPlantView/FormPlaneComponent.cs new file mode 100644 index 0000000..2f6cb3a --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlaneComponent.cs @@ -0,0 +1,122 @@ +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.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 AircraftPlantView +{ + /// + /// Форма для добавление компонента в изделие + /// + public partial class FormPlaneComponent : Form + { + /// + /// Список компонентов + /// + private readonly List? _list; + + /// + /// Идентификатор + /// + public int Id + { + get + { + return Convert.ToInt32(comboBoxComponent.SelectedValue); + } + set + { + comboBoxComponent.SelectedValue = value; + } + } + + /// + /// Модель компонента + /// + public IComponentModel? ComponentModel + { + get + { + if (_list == null) + { + return null; + } + foreach (var elem in _list) + { + if (elem.Id == Id) + { + return elem; + } + } + return null; + } + } + + /// + /// Количество + /// + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set { textBoxCount.Text = value.ToString(); } + } + + /// + /// Конструктор + /// + /// + public FormPlaneComponent(IComponentLogic logic) + { + InitializeComponent(); + + _list = logic.ReadList(null); + if (_list != null) + { + comboBoxComponent.DisplayMember = "ComponentName"; + comboBoxComponent.ValueMember = "Id"; + comboBoxComponent.DataSource = _list; + comboBoxComponent.SelectedItem = null; + } + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxComponent.SelectedValue == null) + { + MessageBox.Show("Выберите компонент", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + DialogResult = DialogResult.OK; + Close(); + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormPlaneComponent.resx b/AircraftPlant/AircraftPlantView/FormPlaneComponent.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlaneComponent.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/AircraftPlant/AircraftPlantView/FormPlanes.Designer.cs b/AircraftPlant/AircraftPlantView/FormPlanes.Designer.cs new file mode 100644 index 0000000..7bb7b6f --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlanes.Designer.cs @@ -0,0 +1,122 @@ +namespace AircraftPlantView +{ + partial class FormPlanes + { + /// + /// 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(); + buttonDelete = new Button(); + buttonRefresh = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(0, 0); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(450, 361); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(480, 12); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(75, 23); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(480, 41); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(75, 23); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(480, 70); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(75, 23); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(480, 99); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(75, 23); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // FormPlanes + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormPlanes"; + Text = "Изделия"; + Load += FormPlanes_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonDelete; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormPlanes.cs b/AircraftPlant/AircraftPlantView/FormPlanes.cs new file mode 100644 index 0000000..ae7f5bd --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlanes.cs @@ -0,0 +1,158 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +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 AircraftPlantView +{ + /// + /// Форма для вывода всех изделий + /// + public partial class FormPlanes : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для изделий + /// + private readonly IPlaneLogic _logic; + + /// + /// Конструктор + /// + /// + /// + public FormPlanes(ILogger logger, IPlaneLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка списка изделий + /// + /// + /// + private void FormPlanes_Load(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Кнопка "Добавить" + /// + /// + /// + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormPlane)); + if (service is FormPlane 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(FormPlane)); + if (service is FormPlane form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + 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 PlaneBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + /// + /// Кнопка "Обновить" + /// + /// + /// + private void buttonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Метод загрузки списка изделий + /// + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["PlaneName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["PlaneComponents"].Visible = false; + } + _logger.LogInformation("Загрузка изделий"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormPlanes.resx b/AircraftPlant/AircraftPlantView/FormPlanes.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormPlanes.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/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index d11019f..90280e1 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -1,7 +1,22 @@ +using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantListImplement.Implements; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; + namespace AircraftPlantView { internal static class Program { + /// + /// IoC- + /// + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; + /// /// The main entry point for the application. /// @@ -11,7 +26,41 @@ namespace AircraftPlantView // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + + var services = new ServiceCollection(); + ConfigureServices(services); + _serviceProvider = services.BuildServiceProvider(); + + Application.Run(_serviceProvider.GetRequiredService()); + } + + /// + /// IoC- + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + + services.AddTransient(); + services.AddTransient(); + 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/AircraftPlant/AircraftPlantView/nlog.config b/AircraftPlant/AircraftPlantView/nlog.config new file mode 100644 index 0000000..cfe664d --- /dev/null +++ b/AircraftPlant/AircraftPlantView/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file