diff --git a/MotorPlant/MotorPlantBusinessLogic/ImplementerLogic.cs b/MotorPlant/MotorPlantBusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..8cbf3a8 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/ImplementerLogic.cs @@ -0,0 +1,128 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage + implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ClientFIO}. 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. 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 Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update 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; + } + 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 (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля клиента", + nameof(model.Password)); + } + if (model.WorkExperience < 0) + { + throw new ArgumentNullException("Стаж меньше 0", + nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentException("Квалификация меньше 0", nameof(model.Qualification)); + } + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}." + + "Password:{ Password}. WorkExperience:{ WorkExperience}. Qualification:{ Qualification}. Id: { Id} ", + model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким ФИО уже есть"); + } + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs index 7b27063..d9afaf6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs @@ -12,12 +12,28 @@ namespace MotorPlantBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - + static readonly object locker = new object(); 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. Id:{ Id}", 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) { @@ -42,7 +58,6 @@ namespace MotorPlantBusinessLogic.BusinessLogics if (_orderStorage.Insert(model) == null) { - model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -51,7 +66,10 @@ namespace MotorPlantBusinessLogic.BusinessLogics public bool TakeOrderInWork(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выполняется); + lock (locker) + { + return ToNextStatus(model, OrderStatus.Выполняется); + } } public bool FinishOrder(OrderBindingModel model) @@ -67,40 +85,22 @@ namespace MotorPlantBusinessLogic.BusinessLogics public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) { CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); if (element == null) { - throw new ArgumentNullException(nameof(element)); - } - - model.EngineId = element.EngineId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); + _logger.LogWarning("Read operation failed"); return false; } + if (element.Status != orderStatus - 1) + { + _logger.LogWarning("Status change operation failed"); + throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); + } model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } + if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now; + if (element.ImplementerId.HasValue) + model.ImplementerId = element.ImplementerId; + _orderStorage.Update(model); return true; } @@ -122,10 +122,6 @@ namespace MotorPlantBusinessLogic.BusinessLogics { throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); - } _logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/WorkModeling.cs b/MotorPlant/MotorPlantBusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..2cdd031 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/WorkModeling.cs @@ -0,0 +1,145 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class WorkModeling : IWorkProcess + { + private readonly ILogger _logger; + private readonly Random _rnd; + private IOrderLogic? _orderLogic; + public WorkModeling(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 + { + Status = + 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); + 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) + { + if (_orderLogic == null || implementer == null) + { + return; + } + try + { + var runOrder = await Task.Run(() => _orderLogic.ReadElement(new + OrderSearchModel + { + ImplementerId = implementer.Id, + 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/MotorPlant/MotorPlantContracts/BindingModels/ImplementerBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..3605434 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,18 @@ +using MotorPlantDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class ImplementerBindingModel : IImplementerModel + { + public int Id { get; set; } + public string ImplementerFIO { get; set; } = string.Empty; + public int WorkExperience { get; set; } = 0; + public int Qualification { get; set; } = 0; + public string Password { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/OrderBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/OrderBindingModel.cs index 94066f0..4556160 100644 --- a/MotorPlant/MotorPlantContracts/BindingModels/OrderBindingModel.cs +++ b/MotorPlant/MotorPlantContracts/BindingModels/OrderBindingModel.cs @@ -7,6 +7,7 @@ namespace MotorPlantContracts.BindingModels { public int Id { get; set; } public int EngineId { get; set; } + public int? ImplementerId { get; set; } = null; public int ClientId { get; set; } public int Count { get; set; } public double Sum { get; set; } diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IImplementerLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..8d6b4d5 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,20 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.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/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IOrderLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IOrderLogic.cs index ca3f8b3..2c1a03d 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -7,6 +7,7 @@ namespace MotorPlantContracts.BusinessLogicsContracts public interface IOrderLogic { List? ReadList(OrderSearchModel? model); + OrderViewModel? ReadElement(OrderSearchModel model); bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IWorkProcess.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..adc6375 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/MotorPlant/MotorPlantContracts/SearchModels/ImplementerSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..7a5b2c9 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } = string.Empty; + public string? Password { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs index 6349f7c..b9b7642 100644 --- a/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs +++ b/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs @@ -1,9 +1,13 @@ -namespace MotorPlantContracts.SearchModels +using MotorPlantDataModels.Enums; + +namespace MotorPlantContracts.SearchModels { public class OrderSearchModel { public int? Id { get; set; } public int? ClientId { get; set; } + public int? ImplementerId { get; set; } + public OrderStatus? Status { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IImplementerStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..1f22644 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,21 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.StoragesContracts +{ + public interface 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/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..ea49efc --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,23 @@ +using MotorPlantDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ImplementerViewModel : IImplementerModel + { + public int Id { get; set; } + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + [DisplayName("Стаж работы")] + public int WorkExperience { get; set; } = 0; + [DisplayName("Квалификация")] + public int Qualification { get; set; } = 0; + [DisplayName("Пароль")] + public string Password { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs index 9d94b38..0ff8575 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs @@ -10,10 +10,13 @@ namespace MotorPlantContracts.ViewModels public int Id { get; set; } public int EngineId { get; set; } public int ClientId { get; set; } + public int? ImplementerId { get; set; } = null; [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; [DisplayName("Двигатель")] public string EngineName { get; set; } = string.Empty; + [DisplayName("Исполнитель")] + public string ImplementerFIO { get; set; } = string.Empty; [DisplayName("Количество")] public int Count { get; set; } [DisplayName("Сумма")] diff --git a/MotorPlant/MotorPlantDataModels/IImplementerModel.cs b/MotorPlant/MotorPlantDataModels/IImplementerModel.cs new file mode 100644 index 0000000..6e6064c --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/IImplementerModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels +{ + public interface IImplementerModel + { + string ImplementerFIO { get; } + string Password { get; } + int WorkExperience { get; } + int Qualification { get; } + } +} diff --git a/MotorPlant/MotorPlantDataModels/IOrderModel.cs b/MotorPlant/MotorPlantDataModels/IOrderModel.cs index 9630507..92bf509 100644 --- a/MotorPlant/MotorPlantDataModels/IOrderModel.cs +++ b/MotorPlant/MotorPlantDataModels/IOrderModel.cs @@ -6,6 +6,7 @@ namespace MotorPlantDataModels.Models { int EngineId { get; } int ClientId { get; } + int? ImplementerId { get; } int Count { get; } double Sum { get; } OrderStatus Status { get; } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implementer.cs b/MotorPlant/MotorPlantDatabaseImplement/Implementer.cs new file mode 100644 index 0000000..cac72c1 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Implementer.cs @@ -0,0 +1,63 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + [Required] + public string ImplementerFIO { get; private set; } = string.Empty; + [Required] + public string Password { get; set; } = string.Empty; + [Required] + public int Qualification { get; set; } = 0; + [Required] + public int WorkExperience { get; set; } = 0; + [ForeignKey("ImplementerId")] + public virtual List Orders { get; set; } = + new(); + 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, + }; + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/ImplementerStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/ImplementerStorage.cs new file mode 100644 index 0000000..3a7ece0 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/ImplementerStorage.cs @@ -0,0 +1,82 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new MotorPlantDataBase(); + 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) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password) && + !model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDataBase(); + return context.Implementers + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || x.Id == model.Id) && + (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)) + ?.GetViewModel; + } + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + return new(); + } + public List GetFullList() + { + using var context = new MotorPlantDataBase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new MotorPlantDataBase(); + 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 MotorPlantDataBase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418195524_InitialCreate.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502194530_InitialCreate.Designer.cs similarity index 82% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418195524_InitialCreate.Designer.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502194530_InitialCreate.Designer.cs index fcf3f9f..443f280 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418195524_InitialCreate.Designer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502194530_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using MotorPlantDatabaseImplement; namespace MotorPlantDatabaseImplement.Migrations { [DbContext(typeof(MotorPlantDataBase))] - [Migration("20240418195524_InitialCreate")] + [Migration("20240502194530_InitialCreate")] partial class InitialCreate { /// @@ -116,6 +116,33 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("EngineComponents"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.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("MotorPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -139,6 +166,9 @@ namespace MotorPlantDatabaseImplement.Migrations b.Property("EngineId") .HasColumnType("int"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -151,6 +181,8 @@ namespace MotorPlantDatabaseImplement.Migrations b.HasIndex("EngineId"); + b.HasIndex("ImplementerId"); + b.ToTable("Orders"); }); @@ -187,9 +219,15 @@ namespace MotorPlantDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("MotorPlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.Navigation("Client"); b.Navigation("Engine"); + + b.Navigation("Implementer"); }); modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Client", b => @@ -208,6 +246,11 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); #pragma warning restore 612, 618 } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418195524_InitialCreate.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502194530_InitialCreate.cs similarity index 81% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418195524_InitialCreate.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502194530_InitialCreate.cs index 7accc3d..b390162 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418195524_InitialCreate.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502194530_InitialCreate.cs @@ -54,6 +54,22 @@ namespace MotorPlantDatabaseImplement.Migrations table.PrimaryKey("PK_Engines", 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), + Qualification = table.Column(type: "int", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "EngineComponents", columns: table => new @@ -93,7 +109,8 @@ namespace MotorPlantDatabaseImplement.Migrations DateCreate = table.Column(type: "datetime2", nullable: false), DateImplement = table.Column(type: "datetime2", nullable: true), EngineId = table.Column(type: "int", nullable: false), - ClientId = table.Column(type: "int", nullable: false) + ClientId = table.Column(type: "int", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true) }, constraints: table => { @@ -110,6 +127,11 @@ namespace MotorPlantDatabaseImplement.Migrations principalTable: "Engines", principalColumn: "Id", onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + column: x => x.ImplementerId, + principalTable: "Implementers", + principalColumn: "Id"); }); migrationBuilder.CreateIndex( @@ -131,6 +153,11 @@ namespace MotorPlantDatabaseImplement.Migrations name: "IX_Orders_EngineId", table: "Orders", column: "EngineId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); } /// @@ -150,6 +177,9 @@ namespace MotorPlantDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Engines"); + + migrationBuilder.DropTable( + name: "Implementers"); } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs index 0991368..4fb27a6 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs @@ -113,6 +113,33 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("EngineComponents"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.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("MotorPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -136,6 +163,9 @@ namespace MotorPlantDatabaseImplement.Migrations b.Property("EngineId") .HasColumnType("int"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -148,6 +178,8 @@ namespace MotorPlantDatabaseImplement.Migrations b.HasIndex("EngineId"); + b.HasIndex("ImplementerId"); + b.ToTable("Orders"); }); @@ -184,9 +216,15 @@ namespace MotorPlantDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("MotorPlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.Navigation("Client"); b.Navigation("Engine"); + + b.Navigation("Implementer"); }); modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Client", b => @@ -205,6 +243,11 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); #pragma warning restore 612, 618 } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs index 5783784..d3574be 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs @@ -16,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-ETBGTEE;Initial Catalog=MotorPlantDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-ETBGTEE;Initial Catalog=MotorPlantDatabase1;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -25,5 +25,6 @@ optionsBuilder) public virtual DbSet EngineComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Implementers { set; get; } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Order.cs index 3824f04..d6416ea 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Order.cs @@ -24,6 +24,8 @@ namespace MotorPlantDatabaseImplement.Models [Required] public int ClientId { get; private set; } public virtual Client Client { get; private set; } + public int? ImplementerId { get; private set; } = null; + public virtual Implementer? Implementer { get; private set; } public static Order? Create(MotorPlantDataBase context, OrderBindingModel model) { if (model == null) @@ -42,6 +44,9 @@ namespace MotorPlantDatabaseImplement.Models Engine = context.Engines.FirstOrDefault(x => x.Id == model.EngineId), ClientId = model.ClientId, Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId), + ImplementerId = model.ImplementerId, + Implementer = (model.ImplementerId.HasValue ? context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId) + : null), }; } public void Update(OrderBindingModel? model) @@ -52,11 +57,13 @@ namespace MotorPlantDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() { EngineId = EngineId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, @@ -64,7 +71,8 @@ namespace MotorPlantDatabaseImplement.Models DateImplement = DateImplement, Id = Id, EngineName = Engine.EngineName, - ClientFIO = Client.ClientFIO + ClientFIO = Client.ClientFIO, + ImplementerFIO = (Implementer != null ? Implementer.ImplementerFIO : string.Empty) }; } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/OrderStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/OrderStorage.cs index 4be4bd7..7b96460 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/OrderStorage.cs @@ -13,21 +13,22 @@ namespace MotorPlantDatabaseImplement.Implements { using var context = new MotorPlantDataBase(); return context.Orders.Include(x => x.Engine) - .Include(x => x.Client).Select(x => x.GetViewModel) + .Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(OrderSearchModel model) { - using var context = new MotorPlantDataBase(); return context.Orders .Include(x => x.Engine) - .Include(x => x.Client).Where(x => ( + .Include(x => x.Client).Include(x => x.Implementer).Where(x => ( (!model.Id.HasValue || x.Id == model.Id) && (!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) && (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId) + && + (!model.Status.HasValue || x.Status == model.Status) ) ) .Select(x => x.GetViewModel) @@ -35,12 +36,11 @@ namespace MotorPlantDatabaseImplement.Implements } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } using var context = new MotorPlantDataBase(); - return context.Orders.Include(x => x.Engine).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return context.Orders.Include(x => x.Engine).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault( + x => ((model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel; } public OrderViewModel? Insert(OrderBindingModel model) { @@ -57,7 +57,7 @@ namespace MotorPlantDatabaseImplement.Implements public OrderViewModel? Update(OrderBindingModel model) { using var context = new MotorPlantDataBase(); - var order = context.Orders.Include(x => x.Engine).Include(x => x.Client).FirstOrDefault(x => x.Id == + var order = context.Orders.Include(x => x.Engine).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id); if (order == null) { diff --git a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs index c8fafdb..73045f0 100644 --- a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs +++ b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs @@ -11,10 +11,12 @@ namespace MotorPlantFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string EngineFileName = "Engine.xml"; private readonly string ClientFileName = "Client.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Engines { get; private set; } public List Clients { get; private set; } + public List Implementers { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -28,6 +30,8 @@ namespace MotorPlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, +"Implementers", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -35,6 +39,8 @@ namespace MotorPlantFileImplement 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) { diff --git a/MotorPlant/MotorPlantFileImplement/Implementer.cs b/MotorPlant/MotorPlantFileImplement/Implementer.cs new file mode 100644 index 0000000..86567e0 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Implementer.cs @@ -0,0 +1,77 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace MotorPlantFileImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + public string ImplementerFIO { get; private set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public int Qualification { get; set; } = 0; + public int WorkExperience { get; set; } = 0; + 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 + }; + public static Implementer? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Implementer() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ImplementerFIO = element.Element("ImplementerFIO")!.Value, + Password = element.Element("Password")!.Value, + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value) + }; + } + public XElement GetXElement => new("Implementer", + new XAttribute("Id", Id), + new XElement("ImplementerFIO", ImplementerFIO), + new XElement("Password", Password), + new XElement("Qualification", Qualification.ToString()), + new XElement("WorkExperience", WorkExperience.ToString()) + ); + } +} diff --git a/MotorPlant/MotorPlantFileImplement/ImplementerStorage.cs b/MotorPlant/MotorPlantFileImplement/ImplementerStorage.cs new file mode 100644 index 0000000..ce2ae7c --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/ImplementerStorage.cs @@ -0,0 +1,83 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantFileImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton source; + public ImplementerStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.Implementers + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(ImplementerSearchModel + model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password)) + { + return new(); + } + return source.Implementers + .Where(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO.Contains(model.ImplementerFIO)) && + (string.IsNullOrEmpty(model.Password) || x.Password.Contains(model.Password))) + .Select(x => x.GetViewModel) + .ToList(); + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + return source.Implementers + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)) + ?.GetViewModel; + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => + x.Id) + 1 : 1; + var newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + source.Implementers.Add(newImplementer); + source.SaveImplementers(); + return newImplementer.GetViewModel; + } + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (implementer == null) + { + return null; + } + implementer.Update(model); + source.SaveImplementers(); + return implementer.GetViewModel; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var element = source.Implementers.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + source.Implementers.Remove(element); + source.SaveImplementers(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/MotorPlant/MotorPlantFileImplement/Order.cs b/MotorPlant/MotorPlantFileImplement/Order.cs index 3d38089..961251f 100644 --- a/MotorPlant/MotorPlantFileImplement/Order.cs +++ b/MotorPlant/MotorPlantFileImplement/Order.cs @@ -10,6 +10,7 @@ namespace MotorPlantFileImplement.Models { public int EngineId { get; private set; } public int ClientId { get; private set; } + public int? ImplementerId { get; private set; } = null; public int Count { get; private set; } public double Sum { get; private set; } public OrderStatus Status { get; private set; } @@ -31,7 +32,8 @@ namespace MotorPlantFileImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement + DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId, }; } public static Order? Create(XElement element) @@ -45,6 +47,7 @@ namespace MotorPlantFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), EngineId = Convert.ToInt32(element.Element("EngineId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.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.ToString()), @@ -66,6 +69,7 @@ namespace MotorPlantFileImplement.Models Id = Id, EngineId = EngineId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/MotorPlant/MotorPlantFileImplement/OrderStorage.cs b/MotorPlant/MotorPlantFileImplement/OrderStorage.cs index a5977cd..0df9256 100644 --- a/MotorPlant/MotorPlantFileImplement/OrderStorage.cs +++ b/MotorPlant/MotorPlantFileImplement/OrderStorage.cs @@ -16,7 +16,7 @@ namespace MotorPlantFileImplement.Implements public List GetFullList() { return source.Orders - .Select(x => AccessEngineStorage(x.GetViewModel)) + .Select(x => AccessStorage(x.GetViewModel)) .ToList(); } public List GetFilteredList(OrderSearchModel @@ -29,9 +29,11 @@ model) (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId) + && + (!model.Status.HasValue || x.Status == model.Status) ) ) - .Select(x => AccessEngineStorage(x.GetViewModel)) + .Select(x => AccessStorage(x.GetViewModel)) .ToList(); } public OrderViewModel? GetElement(OrderSearchModel model) @@ -40,8 +42,11 @@ model) { return null; } - return AccessEngineStorage(source.Orders - .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel); + return AccessStorage(source.Orders + .FirstOrDefault( + x => ((model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel); } public OrderViewModel? Insert(OrderBindingModel model) { @@ -53,7 +58,7 @@ model) } source.Orders.Add(newOrder); source.SaveOrders(); - return AccessEngineStorage(newOrder.GetViewModel); + return AccessStorage(newOrder.GetViewModel); } public OrderViewModel? Update(OrderBindingModel model) { @@ -64,7 +69,7 @@ model) } order.Update(model); source.SaveOrders(); - return AccessEngineStorage(order.GetViewModel); + return AccessStorage(order.GetViewModel); } public OrderViewModel? Delete(OrderBindingModel model) { @@ -74,31 +79,23 @@ model) { source.Orders.Remove(element); source.SaveOrders(); - return AccessEngineStorage(element.GetViewModel); + return AccessStorage(element.GetViewModel); } return null; } - public OrderViewModel AccessEngineStorage(OrderViewModel model) - { - if (model == null) - return null; - foreach (var Engine in source.Engines) - { - if (Engine.Id == model.EngineId) - { - model.EngineName = Engine.EngineName; - break; - } - } - return model; - } - public OrderViewModel AccessClientStorage(OrderViewModel model) + public OrderViewModel AccessStorage(OrderViewModel model) { if (model == null) return null; + var iceCream = source.Engines.FirstOrDefault(x => x.Id == model.Id); var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (iceCream != null) + model.EngineName = iceCream.EngineName; if (client != null) model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; return model; } } diff --git a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs index 8a3b4a6..be17286 100644 --- a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs +++ b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs @@ -10,12 +10,14 @@ namespace MotorPlantListImplement public List Orders { get; set; } public List Engines { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Engines = new List(); Clients = new List(); + Implementers = new List(); } public static DataListSingleton GetInstance() { diff --git a/MotorPlant/MotorPlantListImplement/Implementer.cs b/MotorPlant/MotorPlantListImplement/Implementer.cs new file mode 100644 index 0000000..799e76b --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Implementer.cs @@ -0,0 +1,54 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + public string ImplementerFIO { get; private set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public int WorkExperience { get; set; } = 0; + public int Qualification { get; set; } = 0; + 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/MotorPlant/MotorPlantListImplement/ImplementerStorage.cs b/MotorPlant/MotorPlantListImplement/ImplementerStorage.cs new file mode 100644 index 0000000..e7a17c9 --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/ImplementerStorage.cs @@ -0,0 +1,103 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } + return result; + } + public List GetFilteredList(ImplementerSearchModel + model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password)) + { + return result; + } + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Contains(model.ImplementerFIO)) + { + result.Add(implementer.GetViewModel); + } + } + return result; + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + foreach (var implementer in _source.Implementers) + { + if ((string.IsNullOrEmpty(model.ImplementerFIO) || implementer.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || implementer.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || implementer.Password == model.Password)) + { + return implementer.GetViewModel; + } + } + return null; + } + 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 newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + _source.Implementers.Add(newImplementer); + return newImplementer.GetViewModel; + } + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + foreach (var implementer in _source.Implementers) + { + if (model.Id == implementer.Id) + { + implementer.Update(model); + return implementer.GetViewModel; + } + } + return null; + } + 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; + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Order.cs b/MotorPlant/MotorPlantListImplement/Order.cs index 236b5cc..e0106b8 100644 --- a/MotorPlant/MotorPlantListImplement/Order.cs +++ b/MotorPlant/MotorPlantListImplement/Order.cs @@ -10,6 +10,7 @@ namespace MotorPlantListImplement.Models public int Id { get; private set; } public int EngineId { get; private set; } public int ClientId { get; private set; } + public int? ImplementerId { get; private set; } public int Count { get; private set; } public double Sum { get; private set; } public OrderStatus Status { get; private set; } @@ -31,6 +32,7 @@ namespace MotorPlantListImplement.Models Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId }; } public void Update(OrderBindingModel? model) @@ -46,12 +48,14 @@ namespace MotorPlantListImplement.Models Status = model.Status; DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() { Id = Id, EngineId = EngineId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/MotorPlant/MotorPlantListImplement/OrderStorage.cs b/MotorPlant/MotorPlantListImplement/OrderStorage.cs index a07e482..778f4f0 100644 --- a/MotorPlant/MotorPlantListImplement/OrderStorage.cs +++ b/MotorPlant/MotorPlantListImplement/OrderStorage.cs @@ -18,7 +18,7 @@ namespace MotorPlantListImplement.Implements var result = new List(); foreach (var order in _source.Orders) { - result.Add(AccessEngineStorage(order.GetViewModel)); + result.Add(AccessStorage(order.GetViewModel)); } return result; } @@ -33,7 +33,7 @@ namespace MotorPlantListImplement.Implements (!model.DateTo.HasValue || order.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || order.ClientId == model.ClientId)) ; { - result.Add(AccessEngineStorage(order.GetViewModel)); + result.Add(AccessStorage(order.GetViewModel)); } } return result; @@ -46,9 +46,11 @@ namespace MotorPlantListImplement.Implements } foreach (var order in _source.Orders) { - if (model.Id.HasValue && order.Id == model.Id) + if ((model.Id.HasValue && order.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + order.ImplementerId == model.ImplementerId && order.Status == model.Status)) { - return order.GetViewModel; + return AccessStorage(order.GetViewModel); } } return null; @@ -96,23 +98,19 @@ namespace MotorPlantListImplement.Implements } return null; } - public OrderViewModel AccessEngineStorage(OrderViewModel model) + public OrderViewModel AccessStorage(OrderViewModel model) { - foreach (var Engine in _source.Engines) - { - if (Engine.Id == model.EngineId) - { - model.EngineName = Engine.EngineName; - break; - } - } - return model; - } - public OrderViewModel AccessClientStorage(OrderViewModel model) - { - var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId); + if (model == null) + return null; + var engine = _source.Engines.FirstOrDefault(x => x.Id == model.Id); + var client = _source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = _source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (engine != null) + model.EngineName = engine.EngineName; if (client != null) model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; return model; } } diff --git a/MotorPlant/MotorPlantRestApi/Controllers/ImplementerController.cs b/MotorPlant/MotorPlantRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..5ea440b --- /dev/null +++ b/MotorPlant/MotorPlantRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,105 @@ +using Microsoft.AspNetCore.Mvc; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Enums; +using Microsoft.AspNetCore.Http; +using DocumentFormat.OpenXml.Office2010.Excel; + +namespace MotorPlantRestApi.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : ControllerBase + { + 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 + { + Status = 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/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index 2e28143..8a11f86 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -37,7 +37,9 @@ EngineComponentsToolStripMenuItem = new ToolStripMenuItem(); ListOrdersToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem(); - buttonCreateOrder = new Button(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); @@ -50,7 +52,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, ReportsToolStripMenuItem }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, ReportsToolStripMenuItem, запускРаботToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -60,7 +62,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; toolStripDropDownButton1.Size = new Size(88, 22); @@ -108,6 +110,13 @@ ListOrdersToolStripMenuItem.Text = "Список заказов"; ListOrdersToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 25); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Location = new Point(800, 56); @@ -176,10 +185,17 @@ клиентыToolStripMenuItem.Size = new Size(180, 22); клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(180, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(969, 461); Controls.Add(dataGridView); @@ -216,5 +232,7 @@ private ToolStripMenuItem EngineComponentsToolStripMenuItem; private ToolStripMenuItem ListOrdersToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; - } + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index 4c32854..dc52f26 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -10,12 +10,14 @@ namespace MotorPlantView.Forms private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, 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) { @@ -32,6 +34,8 @@ namespace MotorPlantView.Forms { dataGridView.DataSource = list; dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } @@ -182,5 +186,21 @@ namespace MotorPlantView.Forms 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(ImplementersForm)); + if (service is ImplementersForm form) + { + form.ShowDialog(); + } + } + } } diff --git a/MotorPlant/MotorPlantView/ImplementerForm.Designer.cs b/MotorPlant/MotorPlantView/ImplementerForm.Designer.cs new file mode 100644 index 0000000..4f1ccc4 --- /dev/null +++ b/MotorPlant/MotorPlantView/ImplementerForm.Designer.cs @@ -0,0 +1,162 @@ +namespace MotorPlantView.Forms +{ + partial class ImplementerForm + { + /// + /// 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() + { + FIOTextBox = new TextBox(); + PasswordTextBox = new TextBox(); + QualificationTextBox = new TextBox(); + WorkExperienceTextBox = new TextBox(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // FIOTextBox + // + FIOTextBox.Location = new Point(124, 19); + FIOTextBox.Name = "FIOTextBox"; + FIOTextBox.Size = new Size(411, 27); + FIOTextBox.TabIndex = 0; + // + // PasswordTextBox + // + PasswordTextBox.Location = new Point(124, 52); + PasswordTextBox.Name = "PasswordTextBox"; + PasswordTextBox.Size = new Size(411, 27); + PasswordTextBox.TabIndex = 1; + // + // QualificationTextBox + // + QualificationTextBox.Location = new Point(124, 85); + QualificationTextBox.Name = "QualificationTextBox"; + QualificationTextBox.Size = new Size(411, 27); + QualificationTextBox.TabIndex = 2; + // + // WorkExperienceTextBox + // + WorkExperienceTextBox.Location = new Point(124, 118); + WorkExperienceTextBox.Name = "WorkExperienceTextBox"; + WorkExperienceTextBox.Size = new Size(411, 27); + WorkExperienceTextBox.TabIndex = 3; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(9, 19); + label1.Name = "label1"; + label1.Size = new Size(42, 20); + label1.TabIndex = 4; + label1.Text = "ФИО"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(9, 52); + label2.Name = "label2"; + label2.Size = new Size(62, 20); + label2.TabIndex = 5; + label2.Text = "Пароль"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(9, 85); + label3.Name = "label3"; + label3.Size = new Size(111, 20); + label3.TabIndex = 6; + label3.Text = "Квалификация"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(9, 118); + label4.Name = "label4"; + label4.Size = new Size(99, 20); + label4.TabIndex = 7; + label4.Text = "Стаж работы"; + // + // SaveButton + // + SaveButton.Location = new Point(341, 151); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(94, 29); + SaveButton.TabIndex = 8; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(441, 151); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(94, 29); + CancelButton.TabIndex = 9; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // ImplementerForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(548, 186); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(WorkExperienceTextBox); + Controls.Add(QualificationTextBox); + Controls.Add(PasswordTextBox); + Controls.Add(FIOTextBox); + Name = "ImplementerForm"; + Text = "Исполнитель"; + Load += ImplementerForm_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox FIOTextBox; + private TextBox PasswordTextBox; + private TextBox QualificationTextBox; + private TextBox WorkExperienceTextBox; + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private Button SaveButton; + private Button CancelButton; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/ImplementerForm.cs b/MotorPlant/MotorPlantView/ImplementerForm.cs new file mode 100644 index 0000000..2c05e01 --- /dev/null +++ b/MotorPlant/MotorPlantView/ImplementerForm.cs @@ -0,0 +1,106 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.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 MotorPlantView.Forms +{ + public partial class ImplementerForm : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + public ImplementerForm(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void ImplementerForm_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + var view = _logic.ReadElement(new ImplementerSearchModel + { + Id = + _id.Value + }); + if (view != null) + { + FIOTextBox.Text = view.ImplementerFIO; + PasswordTextBox.Text = view.Password; + QualificationTextBox.Text = view.Qualification.ToString(); + WorkExperienceTextBox.Text = view.WorkExperience.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(FIOTextBox.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(PasswordTextBox.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение компонента"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = FIOTextBox.Text, + Password = PasswordTextBox.Text, + Qualification = Convert.ToInt32(QualificationTextBox.Text), + WorkExperience = Convert.ToInt32(WorkExperienceTextBox.Text), + }; + var operationResult = _id.HasValue ? _logic.Update(model) : + _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/ImplementerForm.resx b/MotorPlant/MotorPlantView/ImplementerForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/ImplementerForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/ImplementersForm.Designer.cs b/MotorPlant/MotorPlantView/ImplementersForm.Designer.cs new file mode 100644 index 0000000..e213662 --- /dev/null +++ b/MotorPlant/MotorPlantView/ImplementersForm.Designer.cs @@ -0,0 +1,114 @@ +namespace MotorPlantView.Forms +{ + partial class ImplementersForm + { + /// + /// 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() + { + dataGridView1 = new DataGridView(); + CreateButton = new Button(); + ChangeButton = new Button(); + DeleteButton = new Button(); + RefreshButton = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit(); + SuspendLayout(); + // + // dataGridView1 + // + dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView1.Location = new Point(12, 12); + dataGridView1.Name = "dataGridView1"; + dataGridView1.RowHeadersWidth = 51; + dataGridView1.RowTemplate.Height = 29; + dataGridView1.Size = new Size(565, 426); + dataGridView1.TabIndex = 0; + // + // CreateButton + // + CreateButton.Location = new Point(583, 12); + CreateButton.Name = "CreateButton"; + CreateButton.Size = new Size(205, 29); + CreateButton.TabIndex = 1; + CreateButton.Text = "Создать"; + CreateButton.UseVisualStyleBackColor = true; + CreateButton.Click += CreateButton_Click; + // + // ChangeButton + // + ChangeButton.Location = new Point(583, 47); + ChangeButton.Name = "ChangeButton"; + ChangeButton.Size = new Size(205, 29); + ChangeButton.TabIndex = 2; + ChangeButton.Text = "Изменить"; + ChangeButton.UseVisualStyleBackColor = true; + ChangeButton.Click += ChangeButton_Click; + // + // DeleteButton + // + DeleteButton.Location = new Point(583, 82); + DeleteButton.Name = "DeleteButton"; + DeleteButton.Size = new Size(205, 29); + DeleteButton.TabIndex = 3; + DeleteButton.Text = "Удалить"; + DeleteButton.UseVisualStyleBackColor = true; + DeleteButton.Click += DeleteButton_Click; + // + // RefreshButton + // + RefreshButton.Location = new Point(583, 117); + RefreshButton.Name = "RefreshButton"; + RefreshButton.Size = new Size(205, 29); + RefreshButton.TabIndex = 4; + RefreshButton.Text = "Обновить"; + RefreshButton.UseVisualStyleBackColor = true; + RefreshButton.Click += RefreshButton_Click; + // + // ImplementersForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(RefreshButton); + Controls.Add(DeleteButton); + Controls.Add(ChangeButton); + Controls.Add(CreateButton); + Controls.Add(dataGridView1); + Name = "ImplementersForm"; + Text = "Исполнители"; + Load += ImplementersForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView1; + private Button CreateButton; + private Button ChangeButton; + private Button DeleteButton; + private Button RefreshButton; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/ImplementersForm.cs b/MotorPlant/MotorPlantView/ImplementersForm.cs new file mode 100644 index 0000000..649c03a --- /dev/null +++ b/MotorPlant/MotorPlantView/ImplementersForm.cs @@ -0,0 +1,120 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView.Forms +{ + public partial class ImplementersForm : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + public ImplementersForm(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void ImplementersForm_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView1.DataSource = list; + dataGridView1.Columns["Id"].Visible = false; + dataGridView1.Columns["ImplementerFIO"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + dataGridView1.Columns["Password"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + dataGridView1.Columns["Qualification"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + dataGridView1.Columns["WorkExperience"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка компонентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void CreateButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(ImplementerForm)); + if (service is ImplementerForm form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + private void ChangeButton_Click(object sender, EventArgs e) + { + if (dataGridView1.SelectedRows.Count == 1) + { + var service = + Program.ServiceProvider?.GetService(typeof(ImplementerForm)); + if (service is ImplementerForm form) + { + form.Id = + Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + private void DeleteButton_Click(object sender, EventArgs e) + { + if (dataGridView1.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = + Convert.ToInt32(dataGridView1.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 RefreshButton_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/MotorPlant/MotorPlantView/ImplementersForm.resx b/MotorPlant/MotorPlantView/ImplementersForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/ImplementersForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index 3f9998d..a4d3282 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -48,8 +48,11 @@ namespace MotorPlantView.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -62,6 +65,8 @@ namespace MotorPlantView.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + services.AddTransient(); + } } } \ No newline at end of file