From e4f26967a4b34404d592450d35fa76dfb4bf0621 Mon Sep 17 00:00:00 2001 From: K Date: Thu, 18 Apr 2024 20:47:34 +0300 Subject: [PATCH 1/2] lab6(beginning) --- .../BusinessLogic/ImplementerLogic.cs | 120 ++++++++++++++++++ .../BindingModels/ImplementerBindingModel.cs | 18 +++ .../BindingModels/OrderBindingModel.cs | 1 + .../IImplementerLogic.cs | 20 +++ .../SearchModels/ImplementerSearchModel.cs | 15 +++ .../SearchModels/OrderSearchModel.cs | 5 +- .../StoragesContracts/IImplementerStorage.cs | 21 +++ .../ViewModels/ImplementerViewModel.cs | 23 ++++ .../ViewModels/OrderViewModel.cs | 3 + .../Models/IImplementerModel.cs | 17 +++ 10 files changed, 242 insertions(+), 1 deletion(-) create mode 100644 PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ImplementerBindingModel.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IImplementerLogic.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ImplementerSearchModel.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IImplementerStorage.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IImplementerModel.cs diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..b2cceb3 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -0,0 +1,120 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.BusinessLogics +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + public bool Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Delete(ImplementerBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}. Id:{ Id}", model.ImplementerFIO, model.Id); + var element = _implementerStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); + var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Нет ФИО исполнителя", nameof(model.ImplementerFIO)); + } + if (model.Qualification <= 0) + { + throw new ArgumentNullException("Квалификация не может быть меньше 0", nameof(model.Qualification)); + } + if (model.WorkExperience <= 0) + { + throw new ArgumentNullException("Стаж работы не модет былть меньше 0", nameof(model.WorkExperience)); + } + _logger.LogInformation("Implementer. ImplementerID:{Id}. ImplementerFIO: {ImplementerFIO}. Password: { Password}. Qualification: {Qualification}. WorkExperience: {WorkExperience}", model.Id, model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Такой исполнитель уже существует"); + } + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ImplementerBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..80d7498 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,18 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class ImplementerBindingModel : IImplementerModel + { + public int Id { get; set; } + public string ImplementerFIO { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public int WorkExperience { get; set; } + public int Qualification { get; set; } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs index 7b2701e..d0fa7ed 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs @@ -13,6 +13,7 @@ namespace PrecastConcretePlantContracts.BindingModels public int Id { get; set; } public int ClientId { get; set; } public int ReinforcedId { get; set; } + public int ImplementerId { get; set; } = 0; public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IImplementerLogic.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..046a23e --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,20 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BusinessLogicsContracts +{ + public interface IImplementerLogic + { + List? ReadList(ImplementerSearchModel? model); + ImplementerViewModel? ReadElement(ImplementerSearchModel model); + bool Create(ImplementerBindingModel model); + bool Update(ImplementerBindingModel model); + bool Delete(ImplementerBindingModel model); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ImplementerSearchModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..1498619 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } + public string? Password { get; set; } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs index c25069e..658d26b 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,5 @@ -using System; +using PrecastConcretePlantDataModels.Enums; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,8 +11,10 @@ namespace PrecastConcretePlantContracts.SearchModels { public int? Id { get; set; } public int? ClientId { get; set; } + public int? ImplementerId { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } + public OrderStatus? Status { get; set; } } } diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IImplementerStorage.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..1d87291 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,21 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.StoragesContracts +{ + public interface IImplementerStorage + { + List GetFullList(); + List GetFilteredList(ImplementerSearchModel model); + ImplementerViewModel? GetElement(ImplementerSearchModel model); + ImplementerViewModel? Insert(ImplementerBindingModel model); + ImplementerViewModel? Update(ImplementerBindingModel model); + ImplementerViewModel? Delete(ImplementerBindingModel model); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..4ba567e --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,23 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.ViewModels +{ + public class ImplementerViewModel : IImplementerModel + { + public int Id { get; set; } + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + [DisplayName("Пароль")] + public string Password { get; set; } = string.Empty; + [DisplayName("Опыт исполнителя")] + public int WorkExperience { get; set; } + [DisplayName("Квалификация исполнителя")] + public int Qualification { get; set; } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs index 086d903..2cb4670 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs @@ -14,8 +14,11 @@ namespace PrecastConcretePlantContracts.ViewModels [DisplayName("Номер")] public int Id { get; set; } public int ClientId { get; set; } + public int ImplementerId { get; set; } = 0; [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; public int ReinforcedId { get; set; } [DisplayName("Изделие")] public string ReinforcedName { get; set; } = string.Empty; diff --git a/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IImplementerModel.cs b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..f8d9c51 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IImplementerModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDataModels.Models +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + string Password { get; } + int WorkExperience { get; } + int Qualification { get; } + + } +} -- 2.25.1 From 0f41c7507695b9c73f496953ec7c0ad4d878ddd0 Mon Sep 17 00:00:00 2001 From: K Date: Thu, 2 May 2024 19:47:10 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=B2=D1=80=D0=BE=D0=B4=D0=B5=20=D0=B3?= =?UTF-8?q?=D0=BE=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/ImplementerLogic.cs | 206 +++--- .../BusinessLogic/OrderLogic.cs | 230 +++---- .../BusinessLogic/WorkModelling.cs | 143 +++++ .../OfficePackage/Implements/SaveToExcel.cs | 589 +++++++++--------- .../OfficePackage/Implements/SaveToWord.cs | 202 +++--- .../BindingModels/OrderBindingModel.cs | 4 +- .../BusinessLogicsContracts/IOrderLogic.cs | 3 +- .../BusinessLogicsContracts/IWorkProcess.cs | 16 + .../SearchModels/OrderSearchModel.cs | 8 +- .../ViewModels/ImplementerViewModel.cs | 4 + .../ViewModels/OrderViewModel.cs | 16 +- .../Models/IOrderModel.cs | 3 +- .../Implements/ClientStorage.cs | 12 +- .../Implements/ComponentStorage.cs | 12 +- .../Implements/ImplementerStorage.cs | 95 +++ .../Implements/OrderStorage.cs | 215 +++---- .../Implements/ReinforcedStorage.cs | 12 +- ....cs => 20240502162703_initial.Designer.cs} | 51 +- ...ialCreate.cs => 20240502162703_initial.cs} | 32 +- ...ecastConcretePlantDataBaseModelSnapshot.cs | 49 +- .../Models/Implementer.cs | 70 +++ .../Models/Order.cs | 53 +- .../Models/Reinforced.cs | 4 +- .../PrecastConcretePlantDatabase.cs | 5 +- ...ecastConcretePlantDatabaseImplement.csproj | 1 - .../DataFileSingleton.cs | 12 +- .../Implements/ImplementerStorage.cs | 96 +++ .../Implements/OrderStorage.cs | 173 ++--- .../Models/Implementer.cs | 86 +++ .../Models/Order.cs | 19 +- .../DataListSingleton.cs | 6 +- .../Implements/ImplementerStorage.cs | 131 ++++ .../Implements/OrderStorage.cs | 294 +++++---- .../Models/Implementer.cs | 60 ++ .../Models/Order.cs | 12 +- .../Controllers/ImplementerController.cs | 104 ++++ .../FormImplementer.Designer.cs | 173 +++++ .../FormImplementer.cs | 109 ++++ .../FormImplementer.resx | 120 ++++ .../FormImplementerS.Designer.cs | 125 ++++ .../FormImplementerS.cs | 112 ++++ .../FormImplementerS.resx | 120 ++++ .../FormMain.Designer.cs | 352 +++++------ .../PrecastConcretePlantView/FormMain.cs | 322 +++++----- .../PrecastConcretePlantView/Program.cs | 12 +- 45 files changed, 3118 insertions(+), 1355 deletions(-) create mode 100644 PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModelling.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IWorkProcess.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ImplementerStorage.cs rename PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/{20240418132942_InitialCreate.Designer.cs => 20240502162703_initial.Designer.cs} (81%) rename PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/{20240418132942_InitialCreate.cs => 20240502162703_initial.cs} (81%) create mode 100644 PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Implementer.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ImplementerStorage.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Implementer.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Implementer.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.Designer.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.resx create mode 100644 PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.Designer.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.cs create mode 100644 PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.resx diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs index b2cceb3..eecc6fa 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -14,107 +14,115 @@ namespace ComputersShopBusinessLogic.BusinessLogics { public class ImplementerLogic : IImplementerLogic { - private readonly ILogger _logger; - private readonly IImplementerStorage _implementerStorage; - public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) - { - _logger = logger; - _implementerStorage = implementerStorage; - } - public bool Create(ImplementerBindingModel model) - { - CheckModel(model); - if (_implementerStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } - public bool Delete(ImplementerBindingModel model) - { - CheckModel(model, false); - _logger.LogInformation("Delete. Id:{Id}", model.Id); - if (_implementerStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); - return false; - } - return true; - } + public bool Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } - public ImplementerViewModel? ReadElement(ImplementerSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}. Id:{ Id}", model.ImplementerFIO, model.Id); - var element = _implementerStorage.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 Delete(ImplementerBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } - public List? ReadList(ImplementerSearchModel? model) - { - _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); - var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. FIO:{FIO}.Id:{ Id}", + model.ImplementerFIO, model.Id); + var element = _implementerStorage.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 Update(ImplementerBindingModel model) - { - CheckModel(model); - if (_implementerStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - private void CheckModel(ImplementerBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (string.IsNullOrEmpty(model.ImplementerFIO)) - { - throw new ArgumentNullException("Нет ФИО исполнителя", nameof(model.ImplementerFIO)); - } - if (model.Qualification <= 0) - { - throw new ArgumentNullException("Квалификация не может быть меньше 0", nameof(model.Qualification)); - } - if (model.WorkExperience <= 0) - { - throw new ArgumentNullException("Стаж работы не модет былть меньше 0", nameof(model.WorkExperience)); - } - _logger.LogInformation("Implementer. ImplementerID:{Id}. ImplementerFIO: {ImplementerFIO}. Password: { Password}. Qualification: {Qualification}. WorkExperience: {WorkExperience}", model.Id, model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience); - var element = _implementerStorage.GetElement(new ImplementerSearchModel - { - ImplementerFIO = model.ImplementerFIO - }); - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Такой исполнитель уже существует"); - } - } - } + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. FIO:{FIO}.Id:{ Id} ", model?.ImplementerFIO, model?.Id); + var list = (model == null) ? _implementerStorage.GetFullList() : + _implementerStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (model.WorkExperience < 0) + { + throw new ArgumentException("Опыт работы не должен быть отрицательным", nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentException("Квалификация не должна быть отрицательной", nameof(model.Qualification)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.ImplementerFIO)); + } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Нет фио исполнителя", nameof(model.ImplementerFIO)); + } + _logger.LogInformation("Implementer. Id: {Id}, FIO: {FIO}", model.Id, model.ImplementerFIO); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким фио уже есть"); + } + } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs index 4711f8b..b95e909 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -13,111 +13,127 @@ using System.Threading.Tasks; namespace PrecastConcretePlantBusinessLogic.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. 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("Invalid order status"); - return false; - } - model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } - public bool TakeOrderInWork(OrderBindingModel model) - { - CheckModel(model, false); - if (_orderStorage.GetElement(new OrderSearchModel { Id = model.Id })?.Status != OrderStatus.Принят) - { - _logger.LogWarning("Invalid order status"); - return false; - } - model.Status = OrderStatus.Выполняется; - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - } - return true; - } - public bool FinishOrder(OrderBindingModel model) - { - CheckModel(model, false); - if (_orderStorage.GetElement(new OrderSearchModel { Id = model.Id })?.Status != OrderStatus.Выполняется) - { - _logger.LogWarning("Invalid order status"); - return false; - } - model.Status = OrderStatus.Готов; - model.DateImplement = DateTime.Now; - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - } - return true; - } - public bool DeliveryOrder(OrderBindingModel model) - { - CheckModel(model, false); - var order = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (order?.Status != OrderStatus.Готов) - { - _logger.LogWarning("Invalid order status"); - return false; - } - model.Status = OrderStatus.Выдан; - model.DateImplement = order.DateImplement; - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - } - return true; - } - private void CheckModel(OrderBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (model.Sum <= 0) - { - throw new ArgumentNullException("Стоимость должна быть больше 0", nameof(model.Sum)); - } - _logger.LogInformation("Order. Id: {Id}. Sum: {Sum}. ReinforcedId: {ReinforcedId}", model.Id, model.Sum, model.ReinforcedId); - var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (element != null && element.Id == model.Id) - { - throw new InvalidOperationException("Заказ с таким номером уже есть"); - } - } - } + public class OrderLogic : IOrderLogic + { + private readonly ILogger _logger; + private readonly IOrderStorage _orderStorage; + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. DateFrom:{DateFrom}. DateTo:{DateTo}. Id:{Id}", model.DateFrom, model.DateTo, model.Id); + var element = _orderStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. 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("Invalid order status"); + return false; + } + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) + { + model.Status = OrderStatus.Неизвестен; + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) + { + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (viewModel.Status + 1 != newStatus) + { + _logger.LogWarning("Change status operation failed"); + throw new InvalidOperationException(); + } + model.Status = newStatus; + if (model.Status == OrderStatus.Готов) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = viewModel.DateImplement; + } + if (viewModel.ImplementerId.HasValue) + { + model.ImplementerId = viewModel.ImplementerId.Value; + } + CheckModel(model, false); + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Change status operation failed"); + return false; + } + return true; + } + public bool TakeOrderInWork(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } + public bool FinishOrder(OrderBindingModel model) + { + model.DateImplement = DateTime.Now; + 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.Sum <= 0) + { + throw new ArgumentNullException("Стоимость должна быть больше 0", nameof(model.Sum)); + } + _logger.LogInformation("Order. Id: {Id}. Sum: {Sum}. ReinforcedId: {ReinforcedId}", model.Id, model.Sum, model.ReinforcedId); + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (element != null && element.Id == model.Id) + { + throw new InvalidOperationException("Заказ с таким номером уже есть"); + } + } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModelling.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModelling.cs new file mode 100644 index 0000000..2f24a9d --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModelling.cs @@ -0,0 +1,143 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantBusinessLogic.BusinessLogics +{ + public class WorkModelling : IWorkProcess + { + private readonly ILogger _logger; + + private readonly Random _rnd; + + private IOrderLogic? _orderLogic; + + public WorkModelling(ILogger logger) + { + _logger = logger; + _rnd = new Random(1000); + } + + public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) + { + _orderLogic = orderLogic; + var implementers = implementerLogic.ReadList(null); + if (implementers == null) + { + _logger.LogWarning("DoWork. Implementers is null"); + return; + } + + var orders = _orderLogic.ReadList(new OrderSearchModel { Statuses = new() { OrderStatus.Принят, OrderStatus.Выполняется } }); + if (orders == null || orders.Count == 0) + { + _logger.LogWarning("DoWork. Orders is null or empty"); + return; + } + _logger.LogDebug("DoWork for {Count} orders", orders.Count); + foreach (var implementer in implementers) + { + Task.Run(() => WorkerWorkAsync(implementer, orders)); + } + } + + /// + /// Имитация работы исполнителя + /// + private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) + { + if (_orderLogic == null || implementer == null) + { + return; + } + await RunOrderInWork(implementer, orders); + + await Task.Run(() => + { + foreach (var order in orders) + { + try + { + _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); + + _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = order.Id, + ImplementerId = implementer.Id + }); + + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = order.Id + }); + + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + }); + } + + /// + /// Ищем заказ, которые уже в работе (вдруг исполнителя прервали) + /// + private async Task RunOrderInWork(ImplementerViewModel implementer, List allOrders) + { + if (_orderLogic == null || implementer == null || allOrders == null || allOrders.Count == 0) + { + return; + } + try + { + + var runOrder = await Task.Run(() => allOrders.FirstOrDefault(x => x.ImplementerId == implementer.Id && x.Status == OrderStatus.Выполняется)); + if (runOrder == null) + { + return; + } + + _logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id); + + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = runOrder.Id + }); + + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs index fc55f81..3dc0ece 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -13,315 +13,298 @@ using System.Threading.Tasks; namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements { - public class SaveToExcel : AbstractSaveToExcel - { - private SpreadsheetDocument? _spreadsheetDocument; + public class SaveToExcel : AbstractSaveToExcel + { + private SpreadsheetDocument? _spreadsheetDocument; + private SharedStringTablePart? _shareStringPart; + private Worksheet? _worksheet; + private static void CreateStyles(WorkbookPart workbookpart) + { + var sp = workbookpart.AddNewPart(); + sp.Stylesheet = new Stylesheet(); + var fonts = new Fonts() { Count = 2U, KnownFonts = true }; + var fontUsual = new Font(); + fontUsual.Append(new FontSize() { Val = 12D }); + fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontUsual.Append(new FontName() { Val = "Times New Roman" }); + fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); + fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + var fontTitle = new Font(); + fontTitle.Append(new Bold()); + fontTitle.Append(new FontSize() { Val = 14D }); + fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontTitle.Append(new FontName() { Val = "Times New Roman" }); + fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); + fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + fonts.Append(fontUsual); + fonts.Append(fontTitle); + var fills = new Fills() { Count = 2U }; + var fill1 = new Fill(); + fill1.Append(new PatternFill() { PatternType = PatternValues.None }); var fill2 = new Fill(); + fill2.Append(new PatternFill() + { + PatternType = PatternValues.Gray125 + }); + fills.Append(fill1); + fills.Append(fill2); + var borders = new Borders() { Count = 2U }; + var borderNoBorder = new Border(); + borderNoBorder.Append(new LeftBorder()); + borderNoBorder.Append(new RightBorder()); + borderNoBorder.Append(new TopBorder()); + borderNoBorder.Append(new BottomBorder()); + borderNoBorder.Append(new DiagonalBorder()); + var borderThin = new Border(); + var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }; + leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() + { Indexed = 64U }); + var rightBorder = new RightBorder() + { + Style = BorderStyleValues.Thin + }; + rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() + { Indexed = 64U }); + var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; + topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() + { Indexed = 64U }); + var bottomBorder = new BottomBorder() + { + Style = BorderStyleValues.Thin + }; + bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() + { Indexed = 64U }); + borderThin.Append(leftBorder); + borderThin.Append(rightBorder); + borderThin.Append(topBorder); + borderThin.Append(bottomBorder); + borderThin.Append(new DiagonalBorder()); + borders.Append(borderNoBorder); + borders.Append(borderThin); + var cellStyleFormats = new CellStyleFormats() { Count = 1U }; + var cellFormatStyle = new CellFormat() + { + NumberFormatId = 0U, + FontId = 0U, + FillId = 0U, + BorderId = 0U + }; + cellStyleFormats.Append(cellFormatStyle); + var cellFormats = new CellFormats() { Count = 3U }; + var cellFormatFont = new CellFormat() + { + NumberFormatId = 0U, + FontId = 0U, + FillId = 0U, + BorderId = 0U, + FormatId = 0U, + ApplyFont = true + }; + var cellFormatFontAndBorder = new CellFormat() + { + NumberFormatId = 0U, + FontId = 0U, + FillId = 0U, + BorderId = 1U, + FormatId = 0U, + ApplyFont = true, + ApplyBorder = true + }; + var cellFormatTitle = new CellFormat() + { + NumberFormatId = 0U, + FontId = 1U, + FillId = 0U, + BorderId = 0U, + FormatId = 0U, + Alignment = new Alignment() + { + Vertical = VerticalAlignmentValues.Center, + WrapText = true, + Horizontal = HorizontalAlignmentValues.Center + }, + ApplyFont = true + }; + cellFormats.Append(cellFormatFont); + cellFormats.Append(cellFormatFontAndBorder); + cellFormats.Append(cellFormatTitle); + var cellStyles = new CellStyles() { Count = 1U }; + cellStyles.Append(new CellStyle() + { + Name = "Normal", + FormatId = 0U, + BuiltinId = 0U + }); + var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U }; - private SharedStringTablePart? _shareStringPart; + var tableStyles = new TableStyles() + { + Count = 0U, + DefaultTableStyle = "TableStyleMedium2", + DefaultPivotStyle = "PivotStyleLight16" + }; + var stylesheetExtensionList = new StylesheetExtensionList(); + var stylesheetExtension1 = new StylesheetExtension() + { + Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" + }; + stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); + stylesheetExtension1.Append(new SlicerStyles() + { + DefaultSlicerStyle = "SlicerStyleLight1" + }); + var stylesheetExtension2 = new StylesheetExtension() + { + Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" + }; + stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); + stylesheetExtension2.Append(new TimelineStyles() + { + DefaultTimelineStyle = "TimeSlicerStyleLight1" + }); + stylesheetExtensionList.Append(stylesheetExtension1); + stylesheetExtensionList.Append(stylesheetExtension2); + sp.Stylesheet.Append(fonts); + sp.Stylesheet.Append(fills); + sp.Stylesheet.Append(borders); + sp.Stylesheet.Append(cellStyleFormats); + sp.Stylesheet.Append(cellFormats); + sp.Stylesheet.Append(cellStyles); + sp.Stylesheet.Append(differentialFormats); + sp.Stylesheet.Append(tableStyles); + sp.Stylesheet.Append(stylesheetExtensionList); + } + /// Получение номера стиля из типа + private static uint GetStyleValue(ExcelStyleInfoType styleInfo) + { + return styleInfo switch + { + ExcelStyleInfoType.Title => 2U, + ExcelStyleInfoType.TextWithBorder => 1U, + ExcelStyleInfoType.Text => 0U, + _ => 0U, + }; + } + protected override void CreateExcel(ExcelInfo info) + { + _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, + SpreadsheetDocumentType.Workbook); + var workbookpart = _spreadsheetDocument.AddWorkbookPart(); + workbookpart.Workbook = new Workbook(); CreateStyles(workbookpart); + _shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType().Any() + ? + _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : + _spreadsheetDocument.WorkbookPart.AddNewPart(); + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } - private Worksheet? _worksheet; + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(new SheetData()); - //Настройка стилей для файла - private static void CreateStyles(WorkbookPart workbookpart) - { - var sp = workbookpart.AddNewPart(); - sp.Stylesheet = new Stylesheet(); - var fonts = new Fonts() { Count = 2U, KnownFonts = true }; - var fontUsual = new Font(); - fontUsual.Append(new FontSize() { Val = 12D }); - fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); - fontUsual.Append(new FontName() { Val = "Times New Roman" }); - fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); - fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); - var fontTitle = new Font(); - fontTitle.Append(new Bold()); - fontTitle.Append(new FontSize() { Val = 14D }); - fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); - fontTitle.Append(new FontName() { Val = "Times New Roman" }); - fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); - fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); - fonts.Append(fontUsual); - fonts.Append(fontTitle); - var fills = new Fills() { Count = 2U }; - var fill1 = new Fill(); - fill1.Append(new PatternFill() { PatternType = PatternValues.None }); var fill2 = new Fill(); - fill2.Append(new PatternFill() - { - PatternType = PatternValues.Gray125 - }); - fills.Append(fill1); - fills.Append(fill2); - var borders = new Borders() { Count = 2U }; - var borderNoBorder = new Border(); - borderNoBorder.Append(new LeftBorder()); - borderNoBorder.Append(new RightBorder()); - borderNoBorder.Append(new TopBorder()); - borderNoBorder.Append(new BottomBorder()); - borderNoBorder.Append(new DiagonalBorder()); - var borderThin = new Border(); - var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }; - leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() - { Indexed = 64U }); - var rightBorder = new RightBorder() - { - Style = BorderStyleValues.Thin - }; - rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() - { Indexed = 64U }); - var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; - topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() - { Indexed = 64U }); - var bottomBorder = new BottomBorder() - { - Style = BorderStyleValues.Thin - }; - bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() - { Indexed = 64U }); - borderThin.Append(leftBorder); - borderThin.Append(rightBorder); - borderThin.Append(topBorder); - borderThin.Append(bottomBorder); - borderThin.Append(new DiagonalBorder()); - borders.Append(borderNoBorder); - borders.Append(borderThin); - var cellStyleFormats = new CellStyleFormats() { Count = 1U }; - var cellFormatStyle = new CellFormat() - { - NumberFormatId = 0U, - FontId = 0U, - FillId = 0U, - BorderId = 0U - }; - cellStyleFormats.Append(cellFormatStyle); - var cellFormats = new CellFormats() { Count = 3U }; - var cellFormatFont = new CellFormat() - { - NumberFormatId = 0U, - FontId = 0U, - FillId = 0U, - BorderId = 0U, - FormatId = 0U, - ApplyFont = true - }; - var cellFormatFontAndBorder = new CellFormat() - { - NumberFormatId = 0U, - FontId = 0U, - FillId = 0U, - BorderId = 1U, - FormatId = 0U, - ApplyFont = true, - ApplyBorder = true - }; - var cellFormatTitle = new CellFormat() - { - NumberFormatId = 0U, - FontId = 1U, - FillId = 0U, - BorderId = 0U, - FormatId = 0U, - Alignment = new Alignment() - { - Vertical = VerticalAlignmentValues.Center, - WrapText = true, - Horizontal = HorizontalAlignmentValues.Center - }, - ApplyFont = true - }; - cellFormats.Append(cellFormatFont); - cellFormats.Append(cellFormatFontAndBorder); - cellFormats.Append(cellFormatTitle); - var cellStyles = new CellStyles() { Count = 1U }; - cellStyles.Append(new CellStyle() - { - Name = "Normal", - FormatId = 0U, - BuiltinId = 0U - }); - var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U }; + var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист" + }; + sheets.Append(sheet); + _worksheet = worksheetPart.Worksheet; + } + protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + var sheetData = _worksheet.GetFirstChild(); + if (sheetData == null) + { + return; + } - var tableStyles = new TableStyles() - { - Count = 0U, - DefaultTableStyle = "TableStyleMedium2", - DefaultPivotStyle = "PivotStyleLight16" - }; - var stylesheetExtensionList = new StylesheetExtensionList(); - var stylesheetExtension1 = new StylesheetExtension() - { - Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" - }; - stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); - stylesheetExtension1.Append(new SlicerStyles() - { - DefaultSlicerStyle = "SlicerStyleLight1" - }); - var stylesheetExtension2 = new StylesheetExtension() - { - Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" - }; - stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); - stylesheetExtension2.Append(new TimelineStyles() - { - DefaultTimelineStyle = "TimeSlicerStyleLight1" - }); - stylesheetExtensionList.Append(stylesheetExtension1); - stylesheetExtensionList.Append(stylesheetExtension2); - sp.Stylesheet.Append(fonts); - sp.Stylesheet.Append(fills); - sp.Stylesheet.Append(borders); - sp.Stylesheet.Append(cellStyleFormats); - sp.Stylesheet.Append(cellFormats); - sp.Stylesheet.Append(cellStyles); - sp.Stylesheet.Append(differentialFormats); - sp.Stylesheet.Append(tableStyles); - sp.Stylesheet.Append(stylesheetExtensionList); - } + Row row; + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } - // Получение номера стиля из типа - private static uint GetStyleValue(ExcelStyleInfoType styleInfo) - { - return styleInfo switch - { - ExcelStyleInfoType.Title => 2U, - ExcelStyleInfoType.TextWithBorder => 1U, - ExcelStyleInfoType.Text => 0U, - _ => 0U, - }; - } - protected override void CreateExcel(ExcelInfo info) - { - _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); + Cell cell; + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { - //Создание книги - var workbookpart = _spreadsheetDocument.AddWorkbookPart(); - workbookpart.Workbook = new Workbook(); CreateStyles(workbookpart); - //Получение/создание хранилища текстов для книги - _shareStringPart = - _spreadsheetDocument.WorkbookPart!.GetPartsOfType().Any() - ? - _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() - : - _spreadsheetDocument.WorkbookPart.AddNewPart(); + Cell? refCell = null; + foreach (Cell rowCell in row.Elements()) + { + if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0) + { + refCell = rowCell; + break; + } + } + var newCell = new Cell() + { + CellReference = excelParams.CellReference + }; + row.InsertBefore(newCell, refCell); + cell = newCell; + } - //Создание SharedStringTable, если таковой нет - if (_shareStringPart.SharedStringTable == null) - { - _shareStringPart.SharedStringTable = new SharedStringTable(); - } + _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); + _shareStringPart.SharedStringTable.Save(); + cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + MergeCells mergeCells; + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + mergeCells.Append(mergeCell); + } + protected override void SaveExcel(ExcelInfo info) + { + if (_spreadsheetDocument == null) + { + return; + } + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Dispose(); + } - //Создание листа в книгу - var worksheetPart = workbookpart.AddNewPart(); - worksheetPart.Worksheet = new Worksheet(new SheetData()); - - //Добавление листа в книгу - var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); - var sheet = new Sheet() - { - Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), - SheetId = 1, - Name = "Лист" - }; - sheets.Append(sheet); - _worksheet = worksheetPart.Worksheet; - } - - protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) - { - if (_worksheet == null || _shareStringPart == null) - { - return; - } - var sheetData = _worksheet.GetFirstChild(); - if (sheetData == null) - { - return; - } - - //Ищем строку либо добавляем ее - Row row; - if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) - { - row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); - } - else - { - row = new Row() { RowIndex = excelParams.RowIndex }; - sheetData.Append(row); - } - - //Ищем нужную ячейку - Cell cell; - if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) - { - cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); - } - else - { - //Все ячейки должны быть последовательно друг за другом. Опеделение после какой вставка - Cell? refCell = null; - foreach (Cell rowCell in row.Elements()) - { - if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0) - { - refCell = rowCell; - break; - } - } - var newCell = new Cell() - { - CellReference = excelParams.CellReference - }; - row.InsertBefore(newCell, refCell); - cell = newCell; - } - - //Вставка нового текста - _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); - _shareStringPart.SharedStringTable.Save(); - cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements().Count() - 1).ToString()); - cell.DataType = new EnumValue(CellValues.SharedString); - cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); - } - - protected override void MergeCells(ExcelMergeParameters excelParams) - { - if (_worksheet == null) - { - return; - } - MergeCells mergeCells; - if (_worksheet.Elements().Any()) - { - mergeCells = _worksheet.Elements().First(); - } - else - { - mergeCells = new MergeCells(); - if (_worksheet.Elements().Any()) - { - _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); - } - else - { - _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); - } - } - var mergeCell = new MergeCell() - { - Reference = new StringValue(excelParams.Merge) - }; - mergeCells.Append(mergeCell); - } - protected override void SaveExcel(ExcelInfo info) - { - if (_spreadsheetDocument == null) - { - return; - } - _spreadsheetDocument.WorkbookPart!.Workbook.Save(); - _spreadsheetDocument.Dispose(); - } - - } + } } \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs index bb9e455..bc8de21 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -1,130 +1,124 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using PrecastConcretePlantBusinessLogic.OfficePackage.HelperEnums; using PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels; -//using Document = DocumentFormat.OpenXml.Wordprocessing.Document; -//using Text = DocumentFormat.OpenXml.Wordprocessing.Text; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using System.Text; +using System.Threading.Tasks; +using static System.Net.Mime.MediaTypeNames; +using Document = DocumentFormat.OpenXml.Wordprocessing.Document; +using Text = DocumentFormat.OpenXml.Wordprocessing.Text; namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements { - public class SaveToWord : AbstractSaveToWord - { - private WordprocessingDocument? _wordDocument; - private Body? _docBody; + public class SaveToWord : AbstractSaveToWord + { + private WordprocessingDocument? _wordDocument; + private Body? _docBody; - //Получение типа выравнивания - private static JustificationValues GetJustificationValues(WordJustificationType type) - { - return type switch - { - WordJustificationType.Both => JustificationValues.Both, - WordJustificationType.Center => JustificationValues.Center, - _ => JustificationValues.Left, - }; - } + private static JustificationValues GetJustificationValues(WordJustificationType type) + { + return type switch + { + WordJustificationType.Both => JustificationValues.Both, + WordJustificationType.Center => JustificationValues.Center, + _ => JustificationValues.Left, + }; + } + private static SectionProperties CreateSectionProperties() + { + var properties = new SectionProperties(); - //Настройки страницы - private static SectionProperties CreateSectionProperties() - { - var properties = new SectionProperties(); + var pageSize = new PageSize + { + Orient = PageOrientationValues.Portrait + }; - var pageSize = new PageSize - { - Orient = PageOrientationValues.Portrait - }; + properties.AppendChild(pageSize); - properties.AppendChild(pageSize); + return properties; + } + private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) + { + if (paragraphProperties == null) + { + return null; + } - return properties; - } + var properties = new ParagraphProperties(); - //Задание форматирования для абзаца - private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) - { - if (paragraphProperties == null) - { - return null; - } + properties.AppendChild(new Justification() + { + Val = GetJustificationValues(paragraphProperties.JustificationType) + }); - var properties = new ParagraphProperties(); + properties.AppendChild(new SpacingBetweenLines + { + LineRule = LineSpacingRuleValues.Auto + }); - properties.AppendChild(new Justification() - { - Val = GetJustificationValues(paragraphProperties.JustificationType) - }); + properties.AppendChild(new Indentation()); - properties.AppendChild(new SpacingBetweenLines - { - LineRule = LineSpacingRuleValues.Auto - }); + var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); + if (!string.IsNullOrEmpty(paragraphProperties.Size)) + { + paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); + } + properties.AppendChild(paragraphMarkRunProperties); - properties.AppendChild(new Indentation()); + return properties; + } + protected override void CreateWord(WordInfo info) + { + _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); + MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); + mainPart.Document = new Document(); + _docBody = mainPart.Document.AppendChild(new Body()); + } + protected override void CreateParagraph(WordParagraph paragraph) + { + if (_docBody == null || paragraph == null) + { + return; + } + var docParagraph = new Paragraph(); - var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); - if (!string.IsNullOrEmpty(paragraphProperties.Size)) - { - paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); - } - properties.AppendChild(paragraphMarkRunProperties); + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); - return properties; - } + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); - protected override void CreateWord(WordInfo info) - { - _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); - MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); - mainPart.Document = new Document(); - _docBody = mainPart.Document.AppendChild(new Body()); - } + var properties = new RunProperties(); + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + docRun.AppendChild(properties); - protected override void CreateParagraph(WordParagraph paragraph) - { - if (_docBody == null || paragraph == null) - { - return; - } - var docParagraph = new Paragraph(); + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); - docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + docParagraph.AppendChild(docRun); + } - foreach (var run in paragraph.Texts) - { - var docRun = new Run(); + _docBody.AppendChild(docParagraph); + } + protected override void SaveWord(WordInfo info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); - var properties = new RunProperties(); - properties.AppendChild(new FontSize { Val = run.Item2.Size }); - if (run.Item2.Bold) - { - properties.AppendChild(new Bold()); - } - docRun.AppendChild(properties); + _wordDocument.MainDocumentPart!.Document.Save(); - docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); - - docParagraph.AppendChild(docRun); - } - - _docBody.AppendChild(docParagraph); - } - protected override void SaveWord(WordInfo info) - { - if (_docBody == null || _wordDocument == null) - { - return; - } - _docBody.AppendChild(CreateSectionProperties()); - - _wordDocument.MainDocumentPart!.Document.Save(); - - _wordDocument.Dispose(); - } - } + _wordDocument.Dispose(); + } + } } - diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs index d0fa7ed..a673640 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/OrderBindingModel.cs @@ -13,10 +13,10 @@ namespace PrecastConcretePlantContracts.BindingModels public int Id { get; set; } public int ClientId { get; set; } public int ReinforcedId { get; set; } - public int ImplementerId { get; set; } = 0; public int Count { get; set; } public double Sum { get; set; } - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + public int? ImplementerId { get; set; } + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime? DateImplement { get; set; } } diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IOrderLogic.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IOrderLogic.cs index 5b3c94b..ff5f96f 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -12,7 +12,8 @@ namespace PrecastConcretePlantContracts.BusinessLogicsContracts public interface IOrderLogic { List? ReadList(OrderSearchModel? model); - bool CreateOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel? model); + bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); bool DeliveryOrder(OrderBindingModel model); diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IWorkProcess.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..8082640 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + /// + /// Запуск работ + /// + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs index 658d26b..a5c0cbe 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/OrderSearchModel.cs @@ -11,10 +11,10 @@ namespace PrecastConcretePlantContracts.SearchModels { public int? Id { get; set; } public int? ClientId { get; set; } - public int? ImplementerId { get; set; } - public DateTime? DateFrom { get; set; } + public int? ImplementerId { get; set; } + public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } - public OrderStatus? Status { get; set; } + public List? Statuses { get; set; } - } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs index 4ba567e..d6ea6ca 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ImplementerViewModel.cs @@ -11,12 +11,16 @@ namespace PrecastConcretePlantContracts.ViewModels public class ImplementerViewModel : IImplementerModel { public int Id { get; set; } + [DisplayName("ФИО исполнителя")] public string ImplementerFIO { get; set; } = string.Empty; + [DisplayName("Пароль")] public string Password { get; set; } = string.Empty; + [DisplayName("Опыт исполнителя")] public int WorkExperience { get; set; } + [DisplayName("Квалификация исполнителя")] public int Qualification { get; set; } } diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs index 2cb4670..6b40e6c 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs @@ -13,23 +13,31 @@ namespace PrecastConcretePlantContracts.ViewModels { [DisplayName("Номер")] public int Id { get; set; } + public int ClientId { get; set; } - public int ImplementerId { get; set; } = 0; [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; - public int ReinforcedId { get; set; } + + public int? ImplementerId { get; set; } + [DisplayName("ФИО исполнителя")] + public string? ImplementerFIO { get; set; } = string.Empty; + + public int ReinforcedId { get; set; } [DisplayName("Изделие")] public string ReinforcedName { 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/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IOrderModel.cs b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IOrderModel.cs index d1aa7b0..3677c7d 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IOrderModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IOrderModel.cs @@ -13,7 +13,8 @@ namespace PrecastConcretePlantDataModels.Models int ClientId { get; } int Count { get; } double Sum { get; } - OrderStatus Status { get; } + int? ImplementerId { get; } + OrderStatus Status { get; } DateTime DateCreate { get; } DateTime? DateImplement { get; } } diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs index 446f00a..863b5e9 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs @@ -16,7 +16,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { public List GetFullList() { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Clients .Include(x => x.Orders) .Select(x => x.GetViewModel) @@ -31,7 +31,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements } if (!string.IsNullOrEmpty(model.Email)) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Clients .Include(x => x.Orders) .Where(x => x.Email.Contains(model.Email)) @@ -43,7 +43,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements public ClientViewModel? GetElement(ClientSearchModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); if (model.Id.HasValue) { return context.Clients @@ -64,7 +64,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { return null; } - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); context.Clients.Add(newClient); context.SaveChanges(); return newClient.GetViewModel; @@ -72,7 +72,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements public ClientViewModel? Update(ClientBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); var client = context.Clients.FirstOrDefault(x => x.Id == model.Id); if (client == null) { @@ -85,7 +85,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements public ClientViewModel? Delete(ClientBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); var element = context.Clients .Include(x => x.Orders) .FirstOrDefault(rec => rec.Id == model.Id); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ComponentStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ComponentStorage.cs index 9bfd4fd..324b8ca 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ComponentStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ComponentStorage.cs @@ -15,7 +15,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { public List GetFullList() { - using var context = new PrecastConcretePlantDataBase();//подключение к бд, далее - запросы + using var context = new PrecastConcretePlantDatabase();//подключение к бд, далее - запросы return context.Components .Select(x => x.GetViewModel) .ToList(); @@ -27,7 +27,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { return new(); } - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Components .Where(x => x.ComponentName.Contains(model.ComponentName)) .Select(x => x.GetViewModel) @@ -39,7 +39,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { return null; } - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Components .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; @@ -51,14 +51,14 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { return null; } - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); context.Components.Add(newComponent); context.SaveChanges(); return newComponent.GetViewModel; } public ComponentViewModel? Update(ComponentBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); var component = context.Components.FirstOrDefault(x => x.Id == model.Id); if (component == null) { @@ -70,7 +70,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements } public ComponentViewModel? Delete(ComponentBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ImplementerStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..824af2d --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,95 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new PrecastConcretePlantDatabase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + context.Implementers.Remove(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + using var context = new PrecastConcretePlantDatabase(); + if (model.Id.HasValue) + return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) + return context.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + if (model.ImplementerFIO != null) + return context.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + if (model.ImplementerFIO != null) + { + using var context = new PrecastConcretePlantDatabase(); + return context.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public List GetFullList() + { + using var context = new PrecastConcretePlantDatabase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new PrecastConcretePlantDatabase(); + var res = Implementer.Create(model); + if (res != null) + { + context.Implementers.Add(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new PrecastConcretePlantDatabase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/OrderStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/OrderStorage.cs index f44ea77..6d0f48d 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/OrderStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/OrderStorage.cs @@ -12,108 +12,115 @@ using System.Threading.Tasks; namespace PrecastConcretePlantDatabaseImplement.Implements { - public class OrderStorage : IOrderStorage - { - public List GetFullList() - { - using var context = new PrecastConcretePlantDataBase(); - return context.Orders - .Include(x => x.Reinforced).Include(x => x.Client).Select(x => x.GetViewModel).ToList(); - } - public List GetFilteredList(OrderSearchModel model) - { - using var context = new PrecastConcretePlantDataBase(); - if (model.Id.HasValue) - { - return context.Orders - .Include(x => x.Reinforced) - .Include(x => x.Client) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); - } - else if (model.DateFrom != null && model.DateTo != null) - { - return context.Orders - .Include(x => x.Reinforced) - .Include(x => x.Client) - .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => x.GetViewModel) - .ToList(); - } - else if (model.ClientId.HasValue) - { - return context.Orders - .Include(x => x.Reinforced) - .Include(x => x.Client) - .Where(x => x.ClientId == model.ClientId) - .Select(x => x.GetViewModel) - .ToList(); - } - else - { - return new(); - } - } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } - using var context = new PrecastConcretePlantDataBase(); - return context.Orders.Include(x => x.Reinforced).Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; - } - public OrderViewModel? Insert(OrderBindingModel model) - { - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - using var context = new PrecastConcretePlantDataBase(); - context.Orders.Add(newOrder); - context.SaveChanges(); - return context.Orders - .Include(x => x.Reinforced) - .Include(x => x.Client) - .FirstOrDefault(x => x.Id == newOrder.Id) - ?.GetViewModel; - } - public OrderViewModel? Update(OrderBindingModel model) - { - using var context = new PrecastConcretePlantDataBase(); - var order = context.Orders.FirstOrDefault(x => x.Id == - model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return context.Orders - .Include(x => x.Reinforced) - .Include(x => x.Client) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - } - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new PrecastConcretePlantDataBase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == - model.Id); - if (element != null) - { - var deletedElement = context.Orders - .Include(x => x.Reinforced) - .Include(x => x.Client) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - context.Orders.Remove(element); - context.SaveChanges(); - return element.GetViewModel; - } - return null; - } - } + public class OrderStorage : IOrderStorage + { + public List GetFullList() + { + using var context = new PrecastConcretePlantDatabase(); + return context.Orders + .Include(x => x.Reinforced).Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(OrderSearchModel model) + { + if (model.Id.HasValue) + { + var result = GetElement(model); + return result != null ? new() { result } : new(); + } + + using var context = new PrecastConcretePlantDatabase(); + IQueryable? queryWhere = null; + + if (model.DateFrom.HasValue && model.DateTo.HasValue) + { + queryWhere = context.Orders + .Where(x => model.DateFrom <= x.DateCreate.Date && + x.DateCreate.Date <= model.DateTo); + } + + else if (model.Statuses != null) + { + queryWhere = context.Orders.Where(x => model.Statuses.Contains(x.Status)); + } + + else if (model.ClientId.HasValue) + { + queryWhere = context.Orders.Where(x => x.ClientId == model.ClientId); + } + + else + { + return new(); + } + + return queryWhere + .Include(x => x.Client) + .Include(x => x.Implementer) + .Select(x => x.GetViewModel) + .ToList(); + } + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + using var context = new PrecastConcretePlantDatabase(); + return context.Orders.Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => + (model.Statuses == null || model.Statuses != null && model.Statuses.Contains(x.Status)) && + model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId || + model.Id.HasValue && x.Id == model.Id + )?.GetViewModel; + } + public OrderViewModel? Insert(OrderBindingModel model) + { + var newOrder = Order.Create(model); + if (newOrder == null) + { + return null; + } + using var context = new PrecastConcretePlantDatabase(); + context.Orders.Add(newOrder); + context.SaveChanges(); + return newOrder.GetViewModel; + } + public OrderViewModel? Update(OrderBindingModel model) + { + using var context = new PrecastConcretePlantDatabase(); + + var order = context.Orders + .Include(x => x.Reinforced) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id); + + if (order == null) + { + return null; + } + + order.Update(model); + context.SaveChanges(); + + return order.GetViewModel; + } + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new PrecastConcretePlantDatabase(); + + var element = context.Orders + .Include(x => x.Reinforced) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(rec => rec.Id == model.Id); + + if (element != null) + { + context.Orders.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs index 8040823..ba25b05 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs @@ -17,7 +17,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { public List GetFullList() { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Reinforceds .Include(x => x.Components)//подтягивание зависимостей вместе с исходной записью(тот же join) .ThenInclude(x => x.Component) @@ -31,7 +31,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { return new(); } - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Reinforceds.Include(x => x.Components) .ThenInclude(x => x.Component) .Where(x => x.ReinforcedName.Contains(model.ReinforcedName)) @@ -46,7 +46,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { return null; } - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Reinforceds .Include(x => x.Components) .ThenInclude(x => x.Component) @@ -56,7 +56,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements } public ReinforcedViewModel? Insert(ReinforcedBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); var newReinforced = Reinforced.Create(context, model); if (newReinforced == null) { @@ -68,7 +68,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements } public ReinforcedViewModel? Update(ReinforcedBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); using var transaction = context.Database.BeginTransaction(); try { @@ -92,7 +92,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements } public ReinforcedViewModel? Delete(ReinforcedBindingModel model) { - using var context = new PrecastConcretePlantDataBase(); + using var context = new PrecastConcretePlantDatabase(); var element = context.Reinforceds .Include(x => x.Components) .FirstOrDefault(rec => rec.Id == model.Id); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240418132942_InitialCreate.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240502162703_initial.Designer.cs similarity index 81% rename from PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240418132942_InitialCreate.Designer.cs rename to PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240502162703_initial.Designer.cs index c1233ab..73db043 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240418132942_InitialCreate.Designer.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240502162703_initial.Designer.cs @@ -11,16 +11,16 @@ using PrecastConcretePlantDatabaseImplement; namespace PrecastConcretePlantDatabaseImplement.Migrations { - [DbContext(typeof(PrecastConcretePlantDataBase))] - [Migration("20240418132942_InitialCreate")] - partial class InitialCreate + [DbContext(typeof(PrecastConcretePlantDatabase))] + [Migration("20240502162703_initial")] + partial class initial { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ReinforcedVersion", "7.0.17") + .HasAnnotation("ProductVersion", "7.0.17") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -70,6 +70,33 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -90,6 +117,9 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("ReinforcedId") .HasColumnType("int"); @@ -103,6 +133,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("ReinforcedId"); b.ToTable("Orders"); @@ -162,6 +194,10 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") .WithMany("Orders") .HasForeignKey("ReinforcedId") @@ -170,6 +206,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Reinforced"); }); @@ -202,6 +240,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Navigation("ReinforcedComponents"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => { b.Navigation("Components"); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240418132942_InitialCreate.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240502162703_initial.cs similarity index 81% rename from PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240418132942_InitialCreate.cs rename to PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240502162703_initial.cs index 19d0e02..30767ab 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240418132942_InitialCreate.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240502162703_initial.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace PrecastConcretePlantDatabaseImplement.Migrations { /// - public partial class InitialCreate : Migration + public partial class initial : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -40,6 +40,22 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations table.PrimaryKey("PK_Components", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImplementerFIO = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false), + Qualification = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "Reinforceds", columns: table => new @@ -63,6 +79,7 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations ClientId = table.Column(type: "int", nullable: false), Count = table.Column(type: "int", nullable: false), Sum = table.Column(type: "float", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true), Status = table.Column(type: "int", nullable: false), DateCreate = table.Column(type: "datetime2", nullable: false), DateImplement = table.Column(type: "datetime2", nullable: true), @@ -77,6 +94,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + column: x => x.ImplementerId, + principalTable: "Implementers", + principalColumn: "Id"); table.ForeignKey( name: "FK_Orders_Reinforceds_ReinforcedId", column: x => x.ReinforcedId, @@ -117,6 +139,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations table: "Orders", column: "ClientId"); + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ReinforcedId", table: "Orders", @@ -145,6 +172,9 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Clients"); + migrationBuilder.DropTable( + name: "Implementers"); + migrationBuilder.DropTable( name: "Components"); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs index 1fe0614..b256618 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs @@ -10,14 +10,14 @@ using PrecastConcretePlantDatabaseImplement; namespace PrecastConcretePlantDatabaseImplement.Migrations { - [DbContext(typeof(PrecastConcretePlantDataBase))] - partial class PrecastConcretePlantDataBaseModelSnapshot : ModelSnapshot + [DbContext(typeof(PrecastConcretePlantDatabase))] + partial class PrecastConcretePlantDatabaseModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ReinforcedVersion", "7.0.17") + .HasAnnotation("ProductVersion", "7.0.17") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -67,6 +67,33 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -87,6 +114,9 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("ReinforcedId") .HasColumnType("int"); @@ -100,6 +130,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("ReinforcedId"); b.ToTable("Orders"); @@ -159,6 +191,10 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") .WithMany("Orders") .HasForeignKey("ReinforcedId") @@ -167,6 +203,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Reinforced"); }); @@ -199,6 +237,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Navigation("ReinforcedComponents"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => { b.Navigation("Components"); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Implementer.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..9167e0b --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,70 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + + [Required] + public string ImplementerFIO { get; private set; } = string.Empty; + + [Required] + public string Password { get; private set; } = string.Empty; + + [Required] + public int WorkExperience { get; private set; } + + [Required] + public int Qualification { get; private set; } + + [ForeignKey("ImplementerId")] + public virtual List Orders { get; set; } = new(); + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification, + }; + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs index e6508c7..e1649f0 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs @@ -19,7 +19,8 @@ namespace PrecastConcretePlantDatabaseImplement.Models public int Count { get; private set; } [Required] public double Sum { get; private set; } - [Required] + public int? ImplementerId { get; set; } + [Required] public OrderStatus Status { get; private set; } [Required] public DateTime DateCreate { get; private set; } @@ -28,8 +29,9 @@ namespace PrecastConcretePlantDatabaseImplement.Models public int ReinforcedId { get; private set; } public virtual Reinforced Reinforced { get; set; } public virtual Client Client { get; set; } + public virtual Implementer? Implementer { get; set; } - public static Order? Create(OrderBindingModel model) + public static Order? Create(OrderBindingModel model) { if (model == null) { @@ -45,7 +47,8 @@ namespace PrecastConcretePlantDatabaseImplement.Models DateCreate = model.DateCreate, DateImplement = model.DateImplement, ReinforcedId = model.ReinforcedId, - }; + ImplementerId = model.ImplementerId, + }; } public void Update(OrderBindingModel? model) @@ -55,21 +58,31 @@ namespace PrecastConcretePlantDatabaseImplement.Models return; } Status = model.Status; - DateImplement = model.DateImplement; - } + DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + } - public OrderViewModel GetViewModel => new() - { - ReinforcedId = ReinforcedId, - ReinforcedName = Reinforced.ReinforcedName, - ClientId = ClientId, - ClientFIO = Client.ClientFIO, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement, - Id = Id, - }; - } -} + public OrderViewModel GetViewModel + { + get + { + using var context = new PrecastConcretePlantDatabase(); + return new OrderViewModel + { + ReinforcedId = ReinforcedId, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty, + ReinforcedName = context.Reinforceds.FirstOrDefault(x => x.Id == ReinforcedId)?.ReinforcedName ?? string.Empty, + ClientId = ClientId, + ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement, + Id = Id, + }; + } + } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs index 33a4d2e..5a11ca1 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs @@ -45,7 +45,7 @@ namespace PrecastConcretePlantDatabaseImplement.Models [ForeignKey("ReinforcedId")] public virtual List Orders { get; set; } = new(); - public static Reinforced Create(PrecastConcretePlantDataBase context, ReinforcedBindingModel model) + public static Reinforced Create(PrecastConcretePlantDatabase context, ReinforcedBindingModel model) { return new Reinforced() { @@ -73,7 +73,7 @@ namespace PrecastConcretePlantDatabaseImplement.Models ReinforcedComponents = ReinforcedComponents }; //метод обновления списка связей(вместо контейнски) - public void UpdateComponents(PrecastConcretePlantDataBase context, ReinforcedBindingModel model) + public void UpdateComponents(PrecastConcretePlantDatabase context, ReinforcedBindingModel model) { var ReinforcedComponents = context.ReinforcedComponents .Where(rec => rec.ReinforcedId == model.Id).ToList(); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs index 9d225bc..84fb5c2 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; namespace PrecastConcretePlantDatabaseImplement { - public class PrecastConcretePlantDataBase : DbContext + public class PrecastConcretePlantDatabase : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { @@ -24,6 +24,7 @@ namespace PrecastConcretePlantDatabaseImplement public virtual DbSet ReinforcedComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Implementers { set; get; } - } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabaseImplement.csproj b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabaseImplement.csproj index c9f313e..672de1f 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabaseImplement.csproj +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabaseImplement.csproj @@ -4,7 +4,6 @@ net6.0 enable enable - true diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs index 15ff682..4fad8a5 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs @@ -15,11 +15,13 @@ namespace PrecastConcretePlantFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string ReinforcedFileName = "Reinforced.xml"; private readonly string ClientFileName = "Client.xml"; - public List Components { get; private set; } + private readonly string ImplementerFileName = "Implementer.xml"; + public List Components { get; private set; } public List Orders { get; private set; } public List Reinforceds { get; private set; } public List Clients { get; private set; } - public static DataFileSingleton GetInstance() + public List Implementers { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -31,13 +33,15 @@ namespace PrecastConcretePlantFileImplement public void SaveReinforceds() => SaveData(Reinforceds, ReinforcedFileName, "Reinforceds", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); - private DataFileSingleton() + public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Reinforceds = LoadData(ReinforcedFileName, "Reinforced", x => Reinforced.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; - } + Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ImplementerStorage.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..07a9d0d --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,96 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantFileImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton _source; + public ImplementerStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + _source.Implementers.Remove(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) + return _source.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + if (model.ImplementerFIO != null) + return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + if (model.ImplementerFIO != null) + { + return _source.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public List GetFullList() + { + return _source.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1; + var res = Implementer.Create(model); + if (res != null) + { + _source.Implementers.Add(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs index e148698..1f0cb25 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs @@ -12,102 +12,113 @@ using System.Xml.Linq; namespace PrecastConcretePlantFileImplement.Implements { - public class OrderStorage : IOrderStorage - { - private readonly DataFileSingleton source; + public class OrderStorage : IOrderStorage + { + private readonly DataFileSingleton source; - public OrderStorage() - { - source = DataFileSingleton.GetInstance(); - } + public OrderStorage() + { + source = DataFileSingleton.GetInstance(); + } - public OrderViewModel? Delete(OrderBindingModel model) - { - var element = source.Orders.FirstOrDefault(x => x.Id == model.Id); + public OrderViewModel? Delete(OrderBindingModel model) + { + var element = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (element != null) - { - source.Orders.Remove(element); - source.SaveOrders(); + if (element != null) + { + source.Orders.Remove(element); + source.SaveOrders(); - return ViewAddReinforcedName(element.GetViewModel); - } + return ViewAddReinforcedName(element.GetViewModel); + } - return null; - } + return null; + } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } - var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } - return ViewAddReinforcedName(order.GetViewModel); - } + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (model.ImplementerId.HasValue && model.Statuses != null) + { + return source.Orders + .FirstOrDefault(x => x.ImplementerId == model.ImplementerId && + model.Statuses.Contains(x.Status)) + ?.GetViewModel; + } + if (model.ImplementerId.HasValue) + { + return source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)?.GetViewModel; + } + if (!model.Id.HasValue) + { + return null; + } + var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + return null; + } + return ViewAddReinforcedName(order.GetViewModel); + } - public List GetFilteredList(OrderSearchModel model) - { + public List GetFilteredList(OrderSearchModel model) + { - if (model.Id.HasValue) - { - return source.Orders.Where(x => x.Id == model.Id).Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); - } - else if (model.DateFrom != null && model.DateTo != null) - { - return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); - } - else if (model.ClientId.HasValue) - { - return source.Orders.Where(x => x.ClientId == model.ClientId).Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); - } - return new(); - } + if (model.Id.HasValue) + { + return source.Orders.Where(x => x.Id == model.Id).Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); + } + else if (model.DateFrom != null && model.DateTo != null) + { + return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); + } + else if (model.ClientId.HasValue) + { + return source.Orders.Where(x => x.ClientId == model.ClientId).Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); + } + return new(); + } - public List GetFullList() - { - return source.Orders.Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); - } + public List GetFullList() + { + return source.Orders.Select(x => ViewAddReinforcedName(x.GetViewModel)).ToList(); + } - public OrderViewModel? Insert(OrderBindingModel model) - { - model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; - var newOrder = Order.Create(model); + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; + var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } + if (newOrder == null) + { + return null; + } - source.Orders.Add(newOrder); - source.SaveOrders(); + source.Orders.Add(newOrder); + source.SaveOrders(); - return ViewAddReinforcedName(newOrder.GetViewModel); - } + return ViewAddReinforcedName(newOrder.GetViewModel); + } - public OrderViewModel? Update(OrderBindingModel model) - { - var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); + public OrderViewModel? Update(OrderBindingModel model) + { + var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } + if (order == null) + { + return null; + } - order.Update(model); - source.SaveOrders(); + order.Update(model); + source.SaveOrders(); - return ViewAddReinforcedName(order.GetViewModel); - } - private OrderViewModel ViewAddReinforcedName(OrderViewModel model) - { - var selectedReinforced = source.Reinforceds.FirstOrDefault(x => x.Id == model.ReinforcedId); - model.ReinforcedName = selectedReinforced?.ReinforcedName; - return model; - } - } + return ViewAddReinforcedName(order.GetViewModel); + } + private OrderViewModel ViewAddReinforcedName(OrderViewModel model) + { + var selectedReinforced = source.Reinforceds.FirstOrDefault(x => x.Id == model.ReinforcedId); + model.ReinforcedName = selectedReinforced?.ReinforcedName; + return model; + } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Implementer.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..ca21d99 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Implementer.cs @@ -0,0 +1,86 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace PrecastConcretePlantFileImplement.Models +{ + public class Implementer : IImplementerModel + { + public string ImplementerFIO { get; private set; } = string.Empty; + + public string Password { get; private set; } = string.Empty; + + public int WorkExperience { get; private set; } + + public int Qualification { get; private set; } + + public int Id { get; private set; } + + public static Implementer? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + ImplementerFIO = element.Element("FIO")!.Value, + Password = element.Element("Password")!.Value, + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), + }; + } + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience + }; + + public XElement GetXElement => new("Client", + new XAttribute("Id", Id), + new XElement("Password", Password), + new XElement("FIO", ImplementerFIO), + new XElement("Qualification", Qualification), + new XElement("WorkExperience", WorkExperience) + ); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Order.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Order.cs index 34a3a4c..0772da8 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Order.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Order.cs @@ -21,8 +21,8 @@ namespace PrecastConcretePlantFileImplement.Models public int Count { get; private set; } public double Sum { get; private set; } - - public OrderStatus Status { get; private set; } + public int? ImplementerId { get; set; } + public OrderStatus Status { get; private set; } public DateTime DateCreate { get; private set; } @@ -38,8 +38,9 @@ namespace PrecastConcretePlantFileImplement.Models { ReinforcedId = model.ReinforcedId, ClientId = model.ClientId, - Count = model.Count, + Count = model.Count, Sum = model.Sum, + ImplementerId = model.ImplementerId, Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, @@ -60,7 +61,8 @@ namespace PrecastConcretePlantFileImplement.Models ReinforcedId = Convert.ToInt32(element.Element("ReinforcedId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), - Status = (OrderStatus)(Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value)), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), + Status = (OrderStatus)(Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value)), DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), DateImplement = (dateImplement == "" || dateImplement is null) ? Convert.ToDateTime(null) : Convert.ToDateTime(dateImplement) }; @@ -73,7 +75,8 @@ namespace PrecastConcretePlantFileImplement.Models } Status = model.Status; DateImplement = model.DateImplement; - } + ImplementerId = model.ImplementerId; + } public OrderViewModel GetViewModel => new() { Id = Id, @@ -81,7 +84,8 @@ namespace PrecastConcretePlantFileImplement.Models ReinforcedId = ReinforcedId, Count = Count, Sum = Sum, - Status = Status, + ImplementerId = ImplementerId, + Status = Status, DateCreate = DateCreate, DateImplement = DateImplement }; @@ -92,7 +96,8 @@ namespace PrecastConcretePlantFileImplement.Models new XElement("ReinforcedId", ReinforcedId.ToString()), new XElement("Count", Count.ToString()), new XElement("Sum", Sum.ToString()), - new XElement("Status", Status.ToString()), + new XElement("ImplementerId", ImplementerId), + new XElement("Status", Status.ToString()), new XElement("DateCreate", DateCreate.ToString()), new XElement("DateImplement", DateImplement.ToString())); } diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs index bcdd47f..898ea66 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs @@ -14,13 +14,15 @@ namespace PrecastConcretePlantListImplement public List Orders { get; set; } public List Reinforceds { get; set; } public List Clients { get; set; } - private DataListSingleton() + public List Implementers { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Reinforceds = new List(); Clients = new List(); - } + Implementers = new List(); + } public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..2ff5412 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,131 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + for (int i = 0; i < _source.Implementers.Count; ++i) + { + if (_source.Implementers[i].Id == model.Id) + { + var element = _source.Implementers[i]; + _source.Implementers.RemoveAt(i); + + return element.GetViewModel; + } + } + return null; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + foreach (var x in _source.Implementers) + { + if (model.Id.HasValue && x.Id == model.Id) + return x.GetViewModel; + + if (model.ImplementerFIO != null && model.Password != null && + x.ImplementerFIO.Equals(model.ImplementerFIO) && + x.Password.Equals(model.Password)) + return x.GetViewModel; + + if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO)) + return x.GetViewModel; + } + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + + if (model.Id.HasValue) + { + var res = GetElement(model); + + return res != null ? new() { res } : new(); + } + + List result = new(); + + if (model.ImplementerFIO != null) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Equals(model.ImplementerFIO)) + { + result.Add(implementer.GetViewModel); + } + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } + + return result; + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = 1; + + foreach (var implementer in _source.Implementers) + { + if (model.Id <= implementer.Id) + { + model.Id = implementer.Id + 1; + } + } + + var res = Implementer.Create(model); + + if (res != null) + { + _source.Implementers.Add(res); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.Id == model.Id) + { + implementer.Update(model); + + return implementer.GetViewModel; + } + } + return null; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs index 9616703..b0719b6 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs @@ -11,124 +11,178 @@ using System.Threading.Tasks; namespace PrecastConcretePlantListImplement.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(ViewAddReinforcedName(order.GetViewModel)); - } - return result; - } - public List GetFilteredList(OrderSearchModel model) - { - var result = new List(); - if (!model.Id.HasValue && (model.DateFrom == null || model.DateTo == null)) - { - return result; - } - foreach (var order in _source.Orders) - { - if (model.Id.HasValue && order.Id == model.Id) - { - result.Add(ViewAddReinforcedName(order.GetViewModel)); - } - } - if (!model.Id.HasValue) - { - foreach (var order in _source.Orders) - { - if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) - { - result.Add(ViewAddReinforcedName(order.GetViewModel)); - } - } - } - else if (!model.ClientId.HasValue) - { - foreach (var order in _source.Orders) - { - if (order.ClientId == model.ClientId) - { - 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 ViewAddReinforcedName(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 ViewAddReinforcedName(newOrder.GetViewModel); - } - public OrderViewModel? Update(OrderBindingModel model) - { - foreach (var order in _source.Orders) - { - if (order.Id == model.Id) - { - order.Update(model); - return ViewAddReinforcedName(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 ViewAddReinforcedName(element.GetViewModel); - } - } - return null; - } - private OrderViewModel ViewAddReinforcedName(OrderViewModel model) - { - var selectedReinforced = _source.Reinforceds.Find(reinforced => reinforced.Id == model.ReinforcedId); - if (selectedReinforced != null) - { - model.ReinforcedName = selectedReinforced.ReinforcedName; - } - return model; - } - } + 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(ViewAddReinforcedName(order.GetViewModel)); + } + return result; + } + public List GetFilteredList(OrderSearchModel model) + { + var result = new List(); + if (!model.Id.HasValue && (model.DateFrom == null || model.DateTo == null)) + { + return result; + } + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + result.Add(ViewAddReinforcedName(order.GetViewModel)); + } + } + if (model.Id.HasValue) + { + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + result.Add(order.GetViewModel); + } + else if (model.ImplementerId.HasValue && order.ImplementerId == model.ImplementerId) + { + result.Add(order.GetViewModel); + } + + else if (model.Statuses != null && model.Statuses.Contains(order.Status)) + { + result.Add(order.GetViewModel); + } + } + } + else if (model.DateFrom != null && model.DateTo != null) + { + foreach (var order in _source.Orders) + { + if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) + { + result.Add(order.GetViewModel); + } + } + } + else if (model.ClientId.HasValue) + { + foreach (var order in _source.Orders) + { + if (order.ClientId == model.ClientId) + { + 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; + } + else if (model.ImplementerId.HasValue && model.Statuses != null && + order.ImplementerId == model.ImplementerId && + model.Statuses.Contains(order.Status)) + { + return GetViewModel(order); + } + + else if (model.ImplementerId.HasValue && + model.ImplementerId == order.ImplementerId) + { + return GetViewModel(order); + } + } + + 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 ViewAddReinforcedName(newOrder.GetViewModel); + } + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); + return ViewAddReinforcedName(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 ViewAddReinforcedName(element.GetViewModel); + } + } + return null; + } + private OrderViewModel ViewAddReinforcedName(OrderViewModel model) + { + var selectedReinforced = _source.Reinforceds.Find(reinforced => reinforced.Id == model.ReinforcedId); + if (selectedReinforced != null) + { + model.ReinforcedName = selectedReinforced.ReinforcedName; + } + return model; + } + private OrderViewModel GetViewModel(Order model) + { + var res = model.GetViewModel; + foreach (var reinforced in _source.Reinforceds) + { + if (reinforced.Id == model.ReinforcedId) + { + res.ReinforcedName = reinforced.ReinforcedName; + break; + } + } + foreach (var client in _source.Clients) + { + if (client.Id == res.ClientId) + { + res.ClientFIO = client.ClientFIO; + break; + } + } + return res; + } + } } diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Implementer.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Implementer.cs new file mode 100644 index 0000000..e9b8019 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Implementer.cs @@ -0,0 +1,60 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + + public string ImplementerFIO { get; private set; } = string.Empty; + + public string Password { get; private set; } = string.Empty; + + public int WorkExperience { get; private set; } + + public int Qualification { get; private set; } + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + }; + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Order.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Order.cs index 7116255..6a4040e 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Order.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Order.cs @@ -17,7 +17,8 @@ namespace PrecastConcretePlantListImplement.Models public int ReinforcedId { get; private set; } public int Count { get; private set; } public double Sum { get; private set; } - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + public int? ImplementerId { get; private set; } + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime? DateImplement { get; private set; } public static Order? Create(OrderBindingModel? model) @@ -33,7 +34,8 @@ namespace PrecastConcretePlantListImplement.Models ReinforcedId = model.ReinforcedId, Count = model.Count, Sum = model.Sum, - Status = model.Status, + ImplementerId = model.ImplementerId, + Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, }; @@ -46,7 +48,8 @@ namespace PrecastConcretePlantListImplement.Models } Status = model.Status; DateImplement = model.DateImplement; - } + ImplementerId = model.ImplementerId; + } public OrderViewModel GetViewModel => new() { Id = Id, @@ -54,7 +57,8 @@ namespace PrecastConcretePlantListImplement.Models ReinforcedId = ReinforcedId, Count = Count, Sum = Sum, - Status = Status, + ImplementerId = ImplementerId, + Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, }; diff --git a/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs b/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..3eed9ab --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,104 @@ +using Microsoft.AspNetCore.Mvc; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Enums; + +namespace PrecastConcretePlantRestApi.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : Controller + { + private readonly ILogger _logger; + private readonly IOrderLogic _order; + private readonly IImplementerLogic _logic; + public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger logger) + { + _logger = logger; + _order = order; + _logic = logic; + } + + [HttpGet] + public ImplementerViewModel? Login(string login, string password) + { + try + { + return _logic.ReadElement(new ImplementerSearchModel + { + ImplementerFIO = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка авторизации сотрудника"); + throw; + } + } + + [HttpGet] + public List? GetNewOrders() + { + try + { + return _order.ReadList(new OrderSearchModel + { + Statuses = new() { OrderStatus.Принят } + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения новых заказов"); + throw; + } + } + + [HttpGet] + public OrderViewModel? GetImplementerOrder(int implementerId) + { + try + { + return _order.ReadElement(new OrderSearchModel + { + ImplementerId = implementerId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); + throw; + } + } + + [HttpPost] + public void TakeOrderInWork(OrderBindingModel model) + { + try + { + _order.TakeOrderInWork(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id); + throw; + } + } + + [HttpPost] + public void FinishOrder(OrderBindingModel model) + { + try + { + _order.FinishOrder(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{Id}", model.Id); + throw; + } + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.Designer.cs new file mode 100644 index 0000000..cc46963 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.Designer.cs @@ -0,0 +1,173 @@ +namespace PrecastConcretePlantView +{ + partial class FormImplementer + { + /// + /// 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() + { + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + textBoxFio = new TextBox(); + textBoxPassword = new TextBox(); + numericUpDownWorkExperience = new NumericUpDown(); + numericUpDownQualification = new NumericUpDown(); + buttonCancel = new Button(); + buttonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); + SuspendLayout(); + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(79, 12); + label1.Name = "label1"; + label1.Size = new Size(37, 15); + label1.TabIndex = 0; + label1.Text = "ФИО:"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(69, 41); + label2.Name = "label2"; + label2.Size = new Size(52, 15); + label2.TabIndex = 1; + label2.Text = "Пароль:"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(78, 68); + label3.Name = "label3"; + label3.Size = new Size(38, 15); + label3.TabIndex = 2; + label3.Text = "Стаж:"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(25, 97); + label4.Name = "label4"; + label4.Size = new Size(91, 15); + label4.TabIndex = 3; + label4.Text = "Квалификация:"; + // + // textBoxFio + // + textBoxFio.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxFio.Location = new Point(127, 9); + textBoxFio.Name = "textBoxFio"; + textBoxFio.Size = new Size(271, 23); + textBoxFio.TabIndex = 4; + // + // textBoxPassword + // + textBoxPassword.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxPassword.Location = new Point(127, 38); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.PasswordChar = '*'; + textBoxPassword.Size = new Size(271, 23); + textBoxPassword.TabIndex = 5; + // + // numericUpDownWorkExperience + // + numericUpDownWorkExperience.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + numericUpDownWorkExperience.Location = new Point(127, 66); + numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; + numericUpDownWorkExperience.Size = new Size(271, 23); + numericUpDownWorkExperience.TabIndex = 6; + // + // numericUpDownQualification + // + numericUpDownQualification.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + numericUpDownQualification.Location = new Point(127, 95); + numericUpDownQualification.Name = "numericUpDownQualification"; + numericUpDownQualification.Size = new Size(271, 23); + numericUpDownQualification.TabIndex = 7; + // + // buttonCancel + // + buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCancel.Location = new Point(309, 138); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(89, 33); + buttonCancel.TabIndex = 8; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonSave.Location = new Point(214, 138); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(89, 33); + buttonSave.TabIndex = 9; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(410, 183); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(numericUpDownQualification); + Controls.Add(numericUpDownWorkExperience); + Controls.Add(textBoxPassword); + Controls.Add(textBoxFio); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Name = "FormImplementer"; + Text = "Добавление / Редактирование исполнителя"; + Load += FormImplementer_Load; + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private TextBox textBoxFio; + private TextBox textBoxPassword; + private NumericUpDown numericUpDownWorkExperience; + private NumericUpDown numericUpDownQualification; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.cs new file mode 100644 index 0000000..37d359a --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.cs @@ -0,0 +1,109 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +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 PrecastConcretePlantView +{ + public partial class FormImplementer : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + + public FormImplementer(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormImplementer_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + var view = _logic.ReadElement(new ImplementerSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxFio.Text = view.ImplementerFIO; + textBoxPassword.Text = view.Password; + numericUpDownQualification.Value = view.Qualification; + numericUpDownWorkExperience.Value = view.WorkExperience; + } + } + 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(textBoxPassword.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxFio.Text)) + { + MessageBox.Show("Заполните фио", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFio.Text, + Password = textBoxPassword.Text, + Qualification = (int)numericUpDownQualification.Value, + WorkExperience = (int)numericUpDownWorkExperience.Value, + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.resx b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementer.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/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.Designer.cs new file mode 100644 index 0000000..e4f253e --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.Designer.cs @@ -0,0 +1,125 @@ +namespace PrecastConcretePlantView +{ + partial class FormImplementerS + { + /// + /// 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() + { + buttonRef = new Button(); + buttonDel = new Button(); + buttonUpd = new Button(); + buttonAdd = new Button(); + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // buttonRef + // + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.Location = new Point(652, 263); + buttonRef.Margin = new Padding(3, 4, 3, 4); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(166, 49); + buttonRef.TabIndex = 9; + buttonRef.Text = "Обновить"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonDel + // + buttonDel.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonDel.Location = new Point(652, 211); + buttonDel.Margin = new Padding(3, 4, 3, 4); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(166, 44); + buttonDel.TabIndex = 8; + buttonDel.Text = "Удалить"; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // + // buttonUpd + // + buttonUpd.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonUpd.Location = new Point(652, 158); + buttonUpd.Margin = new Padding(3, 4, 3, 4); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(166, 45); + buttonUpd.TabIndex = 7; + buttonUpd.Text = "Изменить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonAdd + // + buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonAdd.Location = new Point(652, 110); + buttonAdd.Margin = new Padding(3, 4, 3, 4); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(166, 40); + buttonAdd.TabIndex = 6; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(14, 16); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(632, 403); + dataGridView.TabIndex = 5; + // + // FormImplementerS + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(825, 425); + Controls.Add(buttonRef); + Controls.Add(buttonDel); + Controls.Add(buttonUpd); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Margin = new Padding(3, 4, 3, 4); + Name = "FormImplementerS"; + Text = "Просмотр списка исполнителей"; + Load += FormImplementerS_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.cs new file mode 100644 index 0000000..4b84d84 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.cs @@ -0,0 +1,112 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PrecastConcretePlantView +{ + public partial class FormImplementerS : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + public FormImplementerS(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormImplementerS_Load(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["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка исполнителей"); + } + 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(FormImplementer)); + if (service is FormImplementer form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + private void ButtonDel_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 ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.resx b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormImplementerS.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/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs index 3103e5c..c80e0b4 100644 --- a/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs @@ -20,193 +20,183 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip1 = new MenuStrip(); - справочникToolStripMenuItem = new ToolStripMenuItem(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - изделияToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); - списокЖБИToolStripMenuItem = new ToolStripMenuItem(); - жБИПоКомпонентамToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - buttonRef = new Button(); - buttonIssuedOrder = new Button(); - buttonOrderReady = new Button(); - buttonTakeOrderInWork = new Button(); - buttonCreateOrder = new Button(); - dataGridView = new DataGridView(); - menuStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip1 - // - menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникToolStripMenuItem, отчетыToolStripMenuItem }); - menuStrip1.Location = new Point(0, 0); - menuStrip1.Name = "menuStrip1"; - menuStrip1.Padding = new Padding(6, 3, 0, 3); - menuStrip1.Size = new Size(1100, 30); - menuStrip1.TabIndex = 0; - menuStrip1.Text = "menuStrip1"; - // - // справочникToolStripMenuItem - // - справочникToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem }); - справочникToolStripMenuItem.Name = "справочникToolStripMenuItem"; - справочникToolStripMenuItem.Size = new Size(117, 24); - справочникToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // изделияToolStripMenuItem - // - изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(224, 26); - изделияToolStripMenuItem.Text = "Изделия"; - изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(224, 26); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += списокКлиентовToolStripMenuItem_Click; - // - // отчетыToolStripMenuItem - // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЖБИToolStripMenuItem, жБИПоКомпонентамToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(73, 24); - отчетыToolStripMenuItem.Text = "Отчеты"; - // - // списокЖБИToolStripMenuItem - // - списокЖБИToolStripMenuItem.Name = "списокЖБИToolStripMenuItem"; - списокЖБИToolStripMenuItem.Size = new Size(247, 26); - списокЖБИToolStripMenuItem.Text = "Список ЖБИ"; - списокЖБИToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; - // - // жБИПоКомпонентамToolStripMenuItem - // - жБИПоКомпонентамToolStripMenuItem.Name = "жБИПоКомпонентамToolStripMenuItem"; - жБИПоКомпонентамToolStripMenuItem.Size = new Size(247, 26); - жБИПоКомпонентамToolStripMenuItem.Text = "ЖБИ по компонентам"; - жБИПоКомпонентамToolStripMenuItem.Click += изделияПоКомпонентамToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(247, 26); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // buttonRef - // - buttonRef.Location = new Point(931, 273); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(157, 54); - buttonRef.TabIndex = 23; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += ButtonRef_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(931, 213); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(157, 54); - buttonIssuedOrder.TabIndex = 22; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonOrderReady - // - buttonOrderReady.Location = new Point(931, 153); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(157, 54); - buttonOrderReady.TabIndex = 21; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = true; - buttonOrderReady.Click += ButtonOrderReady_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Location = new Point(931, 93); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(157, 54); - buttonTakeOrderInWork.TabIndex = 20; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(931, 33); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(157, 54); - buttonCreateOrder.TabIndex = 19; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // dataGridView - // - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Dock = DockStyle.Left; - dataGridView.Location = new Point(0, 30); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.Size = new Size(925, 374); - dataGridView.TabIndex = 18; - // - // FormMain - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1100, 404); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip1); - MainMenuStrip = menuStrip1; - Name = "FormMain"; - Text = "Завод ЖБИ"; - Load += FormMain_Load; - menuStrip1.ResumeLayout(false); - menuStrip1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip1 = new MenuStrip(); + справочникToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + списокЖБИToolStripMenuItem = new ToolStripMenuItem(); + жБИПоКомпонентамToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + buttonRef = new Button(); + buttonIssuedOrder = new Button(); + buttonCreateOrder = new Button(); + dataGridView = new DataGridView(); + menuStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Padding = new Padding(6, 3, 0, 3); + menuStrip1.Size = new Size(1100, 30); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; + // + // справочникToolStripMenuItem + // + справочникToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникToolStripMenuItem.Name = "справочникToolStripMenuItem"; + справочникToolStripMenuItem.Size = new Size(117, 24); + справочникToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(224, 26); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // изделияToolStripMenuItem + // + изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; + изделияToolStripMenuItem.Size = new Size(224, 26); + изделияToolStripMenuItem.Text = "Изделия"; + изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(224, 26); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += списокКлиентовToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(224, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЖБИToolStripMenuItem, жБИПоКомпонентамToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(73, 24); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокЖБИToolStripMenuItem + // + списокЖБИToolStripMenuItem.Name = "списокЖБИToolStripMenuItem"; + списокЖБИToolStripMenuItem.Size = new Size(247, 26); + списокЖБИToolStripMenuItem.Text = "Список ЖБИ"; + списокЖБИToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; + // + // жБИПоКомпонентамToolStripMenuItem + // + жБИПоКомпонентамToolStripMenuItem.Name = "жБИПоКомпонентамToolStripMenuItem"; + жБИПоКомпонентамToolStripMenuItem.Size = new Size(247, 26); + жБИПоКомпонентамToolStripMenuItem.Text = "ЖБИ по компонентам"; + жБИПоКомпонентамToolStripMenuItem.Click += изделияПоКомпонентамToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(247, 26); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // buttonRef + // + buttonRef.Location = new Point(931, 153); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(157, 54); + buttonRef.TabIndex = 23; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(931, 93); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(157, 54); + buttonIssuedOrder.TabIndex = 22; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(931, 33); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(157, 54); + buttonCreateOrder.TabIndex = 19; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(0, 30); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.Size = new Size(925, 374); + dataGridView.TabIndex = 18; + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1100, 404); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; + Name = "FormMain"; + Text = "Завод ЖБИ"; + Load += FormMain_Load; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip1; + private MenuStrip menuStrip1; private ToolStripMenuItem справочникToolStripMenuItem; private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem изделияToolStripMenuItem; private Button buttonRef; private Button buttonIssuedOrder; - private Button buttonOrderReady; - private Button buttonTakeOrderInWork; private Button buttonCreateOrder; private DataGridView dataGridView; private ToolStripMenuItem отчетыToolStripMenuItem; @@ -214,5 +204,7 @@ private ToolStripMenuItem жБИПоКомпонентамToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; - } + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + } } \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs index 5c08f91..32bac3f 100644 --- a/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging; using PrecastConcretePlantBusinessLogic.BusinessLogics; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantBusinessLogic.BusinessLogics; using System; using System.Collections.Generic; using System.ComponentModel; @@ -14,181 +15,154 @@ using System.Windows.Forms; namespace PrecastConcretePlantView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ReinforcedId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - } - _logger.LogInformation(" "); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - 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(FormReinforcedS)); - if (service is FormReinforcedS 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(" No{id}. ' '", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id - }); - if (!operationResult) - { - throw new Exception(" . ."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation(" No{id}. ''", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id - }); - if (!operationResult) - { - throw new Exception(" . ."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation(" No{id}. ''", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel - { - Id = id - }); - if (!operationResult) - { - throw new Exception(" . ."); - } - _logger.LogInformation(" No{id} ", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - private void ToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveReinforcedsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ReinforcedId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + } + _logger.LogInformation(" "); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + 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(FormReinforcedS)); + if (service is FormReinforcedS 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 ToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportReinforcedComponents)); - if (service is FormReportReinforcedComponents form) - { - form.ShowDialog(); - } - } + 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(" No{id}. ''", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); + if (!operationResult) + { + throw new Exception(" . ."); + } + _logger.LogInformation(" No{id} ", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveReinforcedsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - private void ToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportReinforcedComponents)); + if (service is FormReportReinforcedComponents form) + { + form.ShowDialog(); + } + } - private void ToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } - } + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic + )) as IImplementerLogic)!, _orderLogic); + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementerS)); + if (service is FormImplementerS form) + { + form.ShowDialog(); + } + } + } } + + + diff --git a/PrecastConcretePlant/PrecastConcretePlantView/Program.cs b/PrecastConcretePlant/PrecastConcretePlantView/Program.cs index e1caea4..305c6cd 100644 --- a/PrecastConcretePlant/PrecastConcretePlantView/Program.cs +++ b/PrecastConcretePlant/PrecastConcretePlantView/Program.cs @@ -8,6 +8,7 @@ using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantDatabaseImplement.Implements; using System; +using ComputersShopBusinessLogic.BusinessLogics; namespace PrecastConcretePlantView { @@ -41,14 +42,17 @@ namespace PrecastConcretePlantView 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(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -62,6 +66,8 @@ namespace PrecastConcretePlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + services.AddTransient(); + } } } \ No newline at end of file -- 2.25.1