diff --git a/BlacksmithWorkshop/BlackmithWorkshopRestApi/BlackmithWorkshopRestApi.csproj b/BlacksmithWorkshop/BlackmithWorkshopRestApi/BlackmithWorkshopRestApi.csproj index d243fd4..973b84d 100644 --- a/BlacksmithWorkshop/BlackmithWorkshopRestApi/BlackmithWorkshopRestApi.csproj +++ b/BlacksmithWorkshop/BlackmithWorkshopRestApi/BlackmithWorkshopRestApi.csproj @@ -1,20 +1,19 @@ - + - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - + + + + - - - - - + + + + - + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlackmithWorkshopRestApi/Program.cs b/BlacksmithWorkshop/BlackmithWorkshopRestApi/Program.cs index 3db3298..ca62755 100644 --- a/BlacksmithWorkshop/BlackmithWorkshopRestApi/Program.cs +++ b/BlacksmithWorkshop/BlackmithWorkshopRestApi/Program.cs @@ -14,10 +14,12 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddControllers(); @@ -47,4 +49,4 @@ app.UseAuthorization(); app.MapControllers(); -app.Run(); \ No newline at end of file +app.Run(); (); \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ImplementerLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..87e76d3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -0,0 +1,167 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.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:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + 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("ReadList. 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; + } + + //проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении передаём как параметр false + 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.Qualification <= 0) + { + throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification)); + } + + //проверка на наличие квалификации + if (model.WorkExperience < 0) + { + throw new ArgumentNullException("Указан некоректный стаж работы", nameof(model.WorkExperience)); + } + + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " + + "Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}", + model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id); + + //для проверка на наличие такого же аккаунта + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); + + //если элемент найден и его Id не совпадает с Id переданного объекта + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким именем уже есть"); + } + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/OrderLogic.cs index b7e1316..703d1e2 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -14,165 +14,194 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopBusinessLogic.BusinessLogic { - public class OrderLogic : IOrderLogic - { - private readonly ILogger _logger; + public class OrderLogic : IOrderLogic + { + private readonly ILogger _logger; - private readonly IOrderStorage _orderStorage; + private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; - _orderStorage = orderStorage; - } + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } - //вывод отфильтрованного списка компонентов - public List? ReadList(OrderSearchModel? model) - { - _logger.LogInformation("ReadList. Id:{Id}", model?.Id); + //вывод отфильтрованного списка компонентов + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. Id:{Id}", model?.Id); - //list хранит весь список в случае, если model пришло со значением null на вход метода - var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); - return null; - } + return null; + } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); + _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } + return list; + } - //создание чека - public bool CreateOrder(OrderBindingModel model) - { - CheckModel(model); + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - if (model.Status != OrderStatus.Неизвестен) - { - _logger.LogWarning("Insert operation failed, incorrect order status"); - return false; - } + _logger.LogInformation("ReadElement. Id:{Id}", model?.Id); - model.Status = OrderStatus.Принят; + var element = _orderStorage.GetElement(model); - if (_orderStorage.Insert(model) == null) - { - model.Status = OrderStatus.Неизвестен; - _logger.LogWarning("Insert operation failed"); - return false; - } + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); - return true; - } + return null; + } - public bool TakeOrderInWork(OrderBindingModel model) - { - return StatusUpdate(model, OrderStatus.Выполняется); - } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); - public bool FinishOrder(OrderBindingModel model) - { - return StatusUpdate(model, OrderStatus.Готов); - } + return element; + } - public bool DeliveryOrder(OrderBindingModel model) - { - return StatusUpdate(model, OrderStatus.Выдан); - } + //создание чека + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); - //проверка на пустоту входного параметра - private void CheckModel(OrderBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + if (model.Status != OrderStatus.Неизвестен) + { + _logger.LogWarning("Insert operation failed, incorrect order status"); + return false; + } - //так как при удалении параметром withParams передаём false - if (!withParams) - { - return; - } + model.Status = OrderStatus.Принят; - //проверка на наличие товаров в заказе - if (model.Count <= 0) - { - throw new ArgumentNullException("В заказе не может быть 0 изделий", nameof(model.Count)); - } + if (_orderStorage.Insert(model) == null) + { + model.Status = OrderStatus.Неизвестен; + _logger.LogWarning("Insert operation failed"); + return false; + } - //проверка на наличие нормальной суммарной стоимости чека - if (model.Sum <= 0) - { - throw new ArgumentNullException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); - } + return true; + } - //проверка корректности id у изделий - if (model.ManufactureId < 0) - { - throw new ArgumentNullException("Некорректный id у изделия", nameof(model.ManufactureId)); - } + public bool TakeOrderInWork(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } - //проверка корректности дат - if (model.DateCreate > model.DateImplement) - { - throw new InvalidOperationException("Дата создания должна быть более ранней, нежели дата завершения"); - } + public bool FinishOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Готов); + } - if (model.ClientId < 0) - { - throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientId)); - } + public bool DeliveryOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выдан); + } - _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}. ClientId:{ClientId}. ManufactureId:{Id}", model.Id, model.Sum, model.ClientId, model.ManufactureId); - } + //проверка на пустоту входного параметра + private void CheckModel(OrderBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - //обновление статуса заказа - public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus) - { - var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + //так как при удалении параметром withParams передаём false + if (!withParams) + { + return; + } - //если не смогли найти указанный заказ по его Id - if (viewModel == null) - { - throw new ArgumentNullException(nameof(model)); - } + //проверка на наличие товаров в заказе + if (model.Count <= 0) + { + throw new ArgumentNullException("В заказе не может быть 0 изделий", nameof(model.Count)); + } - //проверка на возможность обновления статуса на следующий - if (viewModel.Status + 1 != newOrderStatus) - { - _logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect"); - return false; - } + //проверка на наличие нормальной суммарной стоимости чека + if (model.Sum <= 0) + { + throw new ArgumentNullException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); + } - model.Status = newOrderStatus; + //проверка корректности id у изделий + if (model.ManufactureId < 0) + { + throw new ArgumentNullException("Некорректный id у изделия", nameof(model.ManufactureId)); + } - //проверка на выдачу - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - else - { - model.DateImplement = viewModel.DateImplement; - } + //проверка корректности дат + if (model.DateCreate > model.DateImplement) + { + throw new InvalidOperationException("Дата создания должна быть более ранней, нежели дата завершения"); + } - CheckModel(model, false); + if (model.ClientId < 0) + { + throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientId)); + } - //финальная проверка на возможность обновления - if (_orderStorage.Update(model) == null) - { - model.Status--; + _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}. ClientId:{ClientId}. ManufactureId:{Id}", model.Id, model.Sum, model.ClientId, model.ManufactureId); + } - _logger.LogWarning("Update operation failed"); + //обновление статуса заказа + public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus) + { + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - return false; - } + //если не смогли найти указанный заказ по его Id + if (viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } - return true; - } - } + //проверка на возможность обновления статуса на следующий + if (viewModel.Status + 1 != newOrderStatus) + { + _logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect"); + return false; + } + + model.Status = newOrderStatus; + + //не забываем положить id работника + if (viewModel.ImplementerId.HasValue) + { + model.ImplementerId = viewModel.ImplementerId; + } + + //проверка на выдачу + if (model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = viewModel.DateImplement; + } + + CheckModel(model, false); + + //финальная проверка на возможность обновления + if (_orderStorage.Update(model) == null) + { + model.Status--; + + _logger.LogWarning("Update operation failed"); + + return false; + } + + return true; + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/WorkModeling.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..3271836 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/WorkModeling.cs @@ -0,0 +1,161 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.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 * 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); + } + // кто-то мог уже перехватить заказ, игнорируем ошибку + 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 * 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); + } + // заказа может не быть, просто игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs index 31d40e7..706f767 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs @@ -15,6 +15,8 @@ namespace BlacksmithWorkshopContracts.BindingModels public int ClientId { get; set; } + public int? ImplementerId { get; set; } + public int ManufactureId { get; set; } public int Count { get; set; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs index bf9c118..1cf9a35 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -9,17 +9,19 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopContracts.BusinessLogicsContracts { - //бизнес-логика для заказов - public interface IOrderLogic - { - List? ReadList(OrderSearchModel? model); + //бизнес-логика для заказов + public interface IOrderLogic + { + List? ReadList(OrderSearchModel? model); - bool CreateOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel model); - bool TakeOrderInWork(OrderBindingModel model); + bool CreateOrder(OrderBindingModel model); - bool FinishOrder(OrderBindingModel model); + bool TakeOrderInWork(OrderBindingModel model); - bool DeliveryOrder(OrderBindingModel model); - } + bool FinishOrder(OrderBindingModel model); + + bool DeliveryOrder(OrderBindingModel model); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IWorkProcess.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..a7208de --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + //интерфейс для класса, имитирующего работу + public interface IWorkProcess + { + // Запуск работ + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs index 2e5ea0f..86995ff 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,5 @@ -using System; +using BlacksmithWorkshopDataModels.Enums; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -6,18 +7,23 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopContracts.SearchModels { - //для поиска сущности "Заказ" - public class OrderSearchModel - { - //для поиска по идентификатору - public int? Id { get; set; } + //для поиска сущности "Заказ" + public class OrderSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } - //для поиска по клиенту - public int? ClientId { get; set; } + //для поиска по клиенту + public int? ClientId { get; set; } - //два поля для возможности производить выборку - public DateTime? DateFrom { get; set; } + //для поиска по исполнителю + public int? ImplementerId { get; set; } - public DateTime? DateTo { get; set; } - } + //два поля для возможности производить выборку + public DateTime? DateFrom { get; set; } + + public DateTime? DateTo { get; set; } + + public OrderStatus? Status { get; set; } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs index 9cec296..e400b3f 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs @@ -9,35 +9,40 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopContracts.ViewModels { - //класс для отображения пользователю информации о заказах - public class OrderViewModel : IOrderModel - { - [DisplayName("Номер")] - public int Id { get; set; } + //класс для отображения пользователю информации о заказах + public class OrderViewModel : IOrderModel + { + [DisplayName("Номер")] + public int Id { get; set; } - public int ClientId { get; set; } + public int ClientId { get; set; } - public int ManufactureId { get; set; } + public int? ImplementerId { get; set; } - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; + public int ManufactureId { get; set; } - [DisplayName("Изделие")] - public string ManufactureName { get; set; } = string.Empty; + [DisplayName("ФИО клиента")] + public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Количество")] - public int Count { get; set; } + [DisplayName("Изделие")] + public string ManufactureName { get; set; } = string.Empty; - [DisplayName("Сумма")] - public double Sum { get; set; } + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Статус")] - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + [DisplayName("Количество")] + public int Count { get; set; } - [DisplayName("Дата создания")] - public DateTime DateCreate { get; set; } = DateTime.Now; + [DisplayName("Сумма")] + public double Sum { get; set; } - [DisplayName("Дата выполнения")] - public DateTime? DateImplement { get; set; } - } + [DisplayName("Статус")] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + [DisplayName("Дата создания")] + public DateTime DateCreate { get; set; } = DateTime.Now; + + [DisplayName("Дата выполнения")] + public DateTime? DateImplement { get; set; } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs index 1659421..5350605 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs @@ -7,25 +7,31 @@ using BlacksmithWorkshopDataModels.Enums; namespace BlacksmithWorkshopDataModels.Models { - //интерфейс, отвечающий за заказ - public interface IOrderModel : IId - { - //id продукта - int ManufactureId { get; } + //интерфейс, отвечающий за заказ + public interface IOrderModel : IId + { + //id продукта + int ManufactureId { get; } - //кол-во продуктов - int Count { get; } + //id клиента + int ClientId { get; } - //суммарная стоимость продуктов - double Sum { get; } + //id исполнителя + int? ImplementerId { get; } - //статус заказа - OrderStatus Status { get; } + //кол-во продуктов + int Count { get; } - //дата создания заказа - DateTime DateCreate { get; } + //суммарная стоимость продуктов + double Sum { get; } - //дата завершения заказа (не обязательна к указанию сразу) - DateTime? DateImplement { get; } - } + //статус заказа + OrderStatus Status { get; } + + //дата создания заказа + DateTime DateCreate { get; } + + //дата завершения заказа (не обязательна к указанию сразу) + DateTime? DateImplement { get; } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabase.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabase.cs index 088fde8..754d80d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabase.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabase.cs @@ -30,5 +30,8 @@ namespace BlacksmithWorkshopDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { get; set; } - } + + public virtual DbSet Implementers { set; get; } + } } + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/ImplementerStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..805b167 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,128 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public List GetFullList() + { + using var context = new BlacksmithWorkshopDatabase(); + + return context.Implementers + .Include(x => x.Orders) + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + return new(); + } + + using var context = new BlacksmithWorkshopDatabase(); + + return context.Implementers + .Include(x => x.Orders) + .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + using var context = new BlacksmithWorkshopDatabase(); + + if (model.Id.HasValue) + { + return context.Implementers + .Include(x => x.Orders) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + else if (!string.IsNullOrEmpty(model.ImplementerFIO) && !string.IsNullOrEmpty(model.Password)) + { + return context.Implementers + .Include(x => x.Orders) + .FirstOrDefault(x => (x.ImplementerFIO == model.ImplementerFIO && x.Password == model.Password)) + ?.GetViewModel; + } + + return new(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + var newImplementer = Implementer.Create(model); + + if (newImplementer == null) + { + return null; + } + + using var context = new BlacksmithWorkshopDatabase(); + + context.Implementers.Add(newImplementer); + context.SaveChanges(); + + return context.Implementers + .Include(x => x.Orders) + .FirstOrDefault(x => x.Id == newImplementer.Id) + ?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new BlacksmithWorkshopDatabase(); + var order = context.Implementers + .Include(x => x.Orders) + .FirstOrDefault(x => x.Id == model.Id); + + if (order == null) + { + return null; + } + + order.Update(model); + context.SaveChanges(); + + return context.Implementers + .Include(x => x.Orders) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new BlacksmithWorkshopDatabase(); + + var element = context.Implementers + .FirstOrDefault(rec => rec.Id == model.Id); + + if (element != null) + { + // для отображения КОРРЕКТНОЙ ViewModel-и + var deletedElement = context.Implementers + .Include(x => x.Orders) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + + context.Implementers.Remove(element); + context.SaveChanges(); + + return deletedElement; + } + + return null; + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/OrderStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/OrderStorage.cs index 9ec068f..ea6e55c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/OrderStorage.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/OrderStorage.cs @@ -12,137 +12,163 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Implements { - public class OrderStorage : IOrderStorage - { - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new BlacksmithWorkshopDatabase(); + public class OrderStorage : IOrderStorage + { + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new BlacksmithWorkshopDatabase(); - var element = context.Orders - .FirstOrDefault(rec => rec.Id == model.Id); + var element = context.Orders + .FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - // для отображения КОРРЕКТНОЙ ViewModel-и - var deletedElement = context.Orders - .Include(x => x.Manufacture) + if (element != null) + { + // для отображения КОРРЕКТНОЙ ViewModel-и + var deletedElement = context.Orders + .Include(x => x.Manufacture) .Include(x => x.Client) .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; + ?.GetViewModel; - context.Orders.Remove(element); - context.SaveChanges(); + context.Orders.Remove(element); + context.SaveChanges(); - return deletedElement; - } + return deletedElement; + } - return null; - } + return null; + } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } - using var context = new BlacksmithWorkshopDatabase(); + using var context = new BlacksmithWorkshopDatabase(); - return context.Orders - .Include(x => x.Manufacture) + return context.Orders + .Include(x => x.Manufacture) .Include(x => x.Client) - .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) - ?.GetViewModel; - } + .Include(x => x.Implementer) + .FirstOrDefault(x => (model.Status == null || model.Status != null && model.Status == x.Status) && + model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId || + model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } - public List GetFilteredList(OrderSearchModel model) - { + public List GetFilteredList(OrderSearchModel model) + { using var context = new BlacksmithWorkshopDatabase(); if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) - { + { return context.Orders - .Include(x => x.Manufacture) - .Include(x => x.Client) - .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => x.GetViewModel) - .ToList(); + .Include(x => x.Manufacture) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => x.GetViewModel) + .ToList(); } - else if (model.Id.HasValue) - { + else if (model.Id.HasValue) + { return context.Orders - .Include(x => x.Manufacture) - .Include(x => x.Client) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); + .Include(x => x.Manufacture) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); } else if (model.ClientId.HasValue) { return context.Orders .Include(x => x.Manufacture) .Include(x => x.Client) + .Include(x => x.Implementer) .Where(x => x.ClientId == model.ClientId) .Select(x => x.GetViewModel) .ToList(); } + else if (model.ImplementerId.HasValue) + { + return context.Orders + .Include(x => x.Manufacture) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.ImplementerId == model.ImplementerId) + .Select(x => x.GetViewModel) + .ToList(); + } - return new(); + return context.Orders + .Include(x => x.Manufacture) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => model.Status == x.Status) + .Select(x => x.GetViewModel) + .ToList(); } - public List GetFullList() - { - using var context = new BlacksmithWorkshopDatabase(); + public List GetFullList() + { + using var context = new BlacksmithWorkshopDatabase(); - return context.Orders - .Include(x => x.Manufacture) + return context.Orders + .Include(x => x.Manufacture) .Include(x => x.Client) + .Include(x => x.Implementer) .Select(x => x.GetViewModel) - .ToList(); - } + .ToList(); + } - public OrderViewModel? Insert(OrderBindingModel model) - { - var newOrder = Order.Create(model); + public OrderViewModel? Insert(OrderBindingModel model) + { + var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } + if (newOrder == null) + { + return null; + } - using var context = new BlacksmithWorkshopDatabase(); + using var context = new BlacksmithWorkshopDatabase(); - context.Orders.Add(newOrder); - context.SaveChanges(); + context.Orders.Add(newOrder); + context.SaveChanges(); - return context.Orders - .Include(x => x.Manufacture) + return context.Orders + .Include(x => x.Manufacture) .Include(x => x.Client) .FirstOrDefault(x => x.Id == newOrder.Id) - ?.GetViewModel; - } + ?.GetViewModel; + } - public OrderViewModel? Update(OrderBindingModel model) - { - using var context = new BlacksmithWorkshopDatabase(); - var order = context.Orders - .Include(x => x.Manufacture) - .Include(x => x.Client) - .FirstOrDefault(x => x.Id == model.Id); + public OrderViewModel? Update(OrderBindingModel model) + { + using var context = new BlacksmithWorkshopDatabase(); + + var order = context.Orders + .Include(x => x.Manufacture) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id); if (order == null) - { - return null; - } + { + return null; + } - order.Update(model); - context.SaveChanges(); + order.Update(model); + context.SaveChanges(); - return context.Orders - .Include(x => x.Manufacture) + return context.Orders + .Include(x => x.Manufacture) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - } - } -} + ?.GetViewModel; + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..963c158 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,86 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; set; } + + [Required] + public string ImplementerFIO { get; set; } = string.Empty; + + [Required] + public string Password { get; set; } = string.Empty; + + [Required] + public int WorkExperience { get; set; } + + [Required] + public int Qualification { get; 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, + Password = model.Password, + ImplementerFIO = model.ImplementerFIO, + Qualification = model.Qualification, + WorkExperience = model.WorkExperience + }; + } + + public static Implementer Create(ImplementerViewModel model) + { + return new Implementer + { + Id = model.Id, + Password = model.Password, + ImplementerFIO = model.ImplementerFIO, + Qualification = model.Qualification, + WorkExperience = model.WorkExperience + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + + Id = model.Id; + Password = model.Password; + ImplementerFIO = model.ImplementerFIO; + Qualification = model.Qualification; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + ImplementerFIO = ImplementerFIO, + Qualification = Qualification, + WorkExperience = WorkExperience + }; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs index 13a55db..72759fb 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs @@ -20,6 +20,8 @@ namespace BlacksmithWorkshopFileImplement private readonly string ClientFileName = "Client.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; + public List WorkPieces { get; private set; } public List Orders { get; private set; } @@ -28,6 +30,8 @@ namespace BlacksmithWorkshopFileImplement public List Clients { get; private set; } + public List Implementers { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -46,12 +50,15 @@ namespace BlacksmithWorkshopFileImplement public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + private DataFileSingleton() { WorkPieces = LoadData(WorkPieceFileName, "WorkPiece", x => WorkPiece.Create(x)!)!; Manufactures = LoadData(ManufactureFileName, "Manufacture", x => Manufacture.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) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/ImplementerStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..199249b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,90 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopFileImplement.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) + { + return source.Implementers.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + + return source.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.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(x => x.Id == model.Id); + + if (element != null) + { + source.Implementers.Remove(element); + source.SaveImplementers(); + + return element.GetViewModel; + } + + return null; + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/OrderStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/OrderStorage.cs index 930071d..9405d70 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/OrderStorage.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/OrderStorage.cs @@ -11,124 +11,138 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopFileImplement.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 List GetFullList() - { - return source.Orders.Select(x => GetViewModel(x)).ToList(); - } + public List GetFullList() + { + return source.Orders.Select(x => GetViewModel(x)).ToList(); + } - public List GetFilteredList(OrderSearchModel model) - { - if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) - { - return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => GetViewModel(x)) - .ToList(); - } - else if (model.Id.HasValue) - { - return source.Orders - .Where(x => x.Id == model.Id) - .Select(x => GetViewModel(x)) - .ToList(); - } - else if (model.ClientId.HasValue) - { - return source.Orders - .Where(x => x.ClientId == model.ClientId) - .Select(x => GetViewModel(x)) - .ToList(); - } + public List GetFilteredList(OrderSearchModel model) + { + if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) + { + return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => GetViewModel(x)) + .ToList(); + } + else if (model.Id.HasValue) + { + return source.Orders + .Where(x => x.Id == model.Id) + .Select(x => GetViewModel(x)) + .ToList(); + } + else if (model.ClientId.HasValue) + { + return source.Orders + .Where(x => x.ClientId == model.ClientId) + .Select(x => GetViewModel(x)) + .ToList(); + } + else if (model.ImplementerId.HasValue) + { + return source.Orders + .Where(x => x.ImplementerId == model.ImplementerId) + .Select(x => GetViewModel(x)) + .ToList(); + } - return new(); - } + return new(); + } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } - return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; - } + return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } - //для загрузки названий изделия в заказе - private OrderViewModel GetViewModel(Order order) - { - var viewModel = order.GetViewModel; + //для загрузки названий и имён в заказ + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; - var manufacture = source.Manufactures.FirstOrDefault(x => x.Id == order.ManufactureId); + var manufacture = source.Manufactures.FirstOrDefault(x => x.Id == order.ManufactureId); - var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId); + var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId); - if (manufacture != null) - { - viewModel.ManufactureName = manufacture.ManufactureName; - } + var implementer = source.Implementers.FirstOrDefault(x => x.Id == order.ImplementerId); - if (client != null) - { - viewModel.ClientFIO = client.ClientFIO; - } + if (manufacture != null) + { + viewModel.ManufactureName = manufacture.ManufactureName; + } - return viewModel; - } + if (client != null) + { + viewModel.ClientFIO = client.ClientFIO; + } - public OrderViewModel? Insert(OrderBindingModel model) - { - model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; + if (implementer != null) + { + viewModel.ImplementerFIO = implementer.ImplementerFIO; + } - var newOrder = Order.Create(model); + return viewModel; + } - if (newOrder == null) - { - return null; - } + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; - source.Orders.Add(newOrder); - source.SaveOrders(); + var newOrder = Order.Create(model); - return GetViewModel(newOrder); - } + if (newOrder == null) + { + return null; + } - public OrderViewModel? Update(OrderBindingModel model) - { - var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); + source.Orders.Add(newOrder); + source.SaveOrders(); - if (order == null) - { - return null; - } + return GetViewModel(newOrder); + } - order.Update(model); - source.SaveOrders(); + public OrderViewModel? Update(OrderBindingModel model) + { + var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); - return GetViewModel(order); - } + if (order == null) + { + return null; + } - public OrderViewModel? Delete(OrderBindingModel model) - { - var element = source.Orders.FirstOrDefault(x => x.Id == model.Id); + order.Update(model); + source.SaveOrders(); - if (element != null) - { - source.Orders.Remove(element); - source.SaveOrders(); + return GetViewModel(order); + } - return GetViewModel(element); - } + public OrderViewModel? Delete(OrderBindingModel model) + { + var element = source.Orders.FirstOrDefault(x => x.Id == model.Id); - return null; - } - } + if (element != null) + { + source.Orders.Remove(element); + source.SaveOrders(); + + return GetViewModel(element); + } + + return null; + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..9c09e35 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs @@ -0,0 +1,90 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace BlacksmithWorkshopFileImplement.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 Implementer() + { + Id = model.Id, + Password = model.Password, + ImplementerFIO = model.ImplementerFIO, + Qualification = model.Qualification, + WorkExperience = model.WorkExperience + }; + } + + public static Implementer? Create(XElement element) + { + if (element == null) + { + return null; + } + + return new Implementer() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + Password = element.Element("Password")!.Value, + ImplementerFIO = element.Element("ImplementerFIO")!.Value, + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value) + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + + Id = model.Id; + Password = model.Password; + ImplementerFIO = model.ImplementerFIO; + Qualification = model.Qualification; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + ImplementerFIO = ImplementerFIO, + Qualification = Qualification, + WorkExperience = WorkExperience + }; + + public XElement GetXElement => new("Order", + new XAttribute("Id", Id), + new XElement("Password", Password), + new XElement("ImplementerFIO", ImplementerFIO), + new XElement("Qualification", Qualification), + new XElement("WorkExperience", WorkExperience)); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs index ee17b60..0c9df8c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs @@ -12,97 +12,103 @@ using System.Xml.Linq; namespace BlacksmithWorkshopFileImplement.Models { - //класс, реализующий интерфейс модели заказа - public class Order : IOrderModel - { - public int Id { get; private set; } + //класс, реализующий интерфейс модели заказа + public class Order : IOrderModel + { + public int Id { get; private set; } - public int ClientId { get; private set; } + public int ClientId { get; private set; } - public int ManufactureId { get; private set; } + public int? ImplementerId { get; private set; } - public int Count { get; private set; } + public int ManufactureId { get; private set; } - public double Sum { get; private set; } + public int Count { get; private set; } - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + public double Sum { get; private set; } - public DateTime DateCreate { get; private set; } = DateTime.Now; + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - public DateTime? DateImplement { get; private set; } + public DateTime DateCreate { get; private set; } = DateTime.Now; - public static Order? Create(OrderBindingModel model) - { - if (model == null) - { - return null; - } + public DateTime? DateImplement { get; private set; } - return new Order() - { - Id = model.Id, - ClientId = model.ClientId, - ManufactureId = model.ManufactureId, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; - } + public static Order? Create(OrderBindingModel model) + { + if (model == null) + { + return null; + } - public static Order? Create(XElement element) - { - if (element == null) - { - return null; - } + return new Order() + { + Id = model.Id, + ClientId = model.ClientId, + ManufactureId = model.ManufactureId, + ImplementerId = model.ImplementerId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } - return new Order() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ClientId = Convert.ToInt32(element.Attribute("Id")!.Value), - ManufactureId = Convert.ToInt32(element.Element("ManufactureId")!.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), - DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), - DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : - Convert.ToDateTime(element.Element("DateImplement")!.Value) - }; - } + public static Order? Create(XElement element) + { + if (element == null) + { + return null; + } - public void Update(OrderBindingModel model) - { - if (model == null) - { - return; - } + return new Order() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + ImplementerId = Convert.ToInt32(element.Attribute("ImplementerId")!.Value), + ManufactureId = Convert.ToInt32(element.Element("ManufactureId")!.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), + DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), + DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : + Convert.ToDateTime(element.Element("DateImplement")!.Value) + }; + } - Status = model.Status; - DateImplement = model.DateImplement; - } + public void Update(OrderBindingModel model) + { + if (model == null) + { + return; + } - public OrderViewModel GetViewModel => new() - { - Id = Id, - ClientId = ClientId, - ManufactureId = ManufactureId, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement - }; + Status = model.Status; + DateImplement = model.DateImplement; + } - public XElement GetXElement => new("Order", - new XAttribute("Id", Id), - new XElement("ClientId", ClientId.ToString()), - new XElement("ManufactureId", ManufactureId.ToString()), - new XElement("Count", Count.ToString()), - new XElement("Sum", Sum.ToString()), - new XElement("Status", Status.ToString()), - new XElement("DateCreate", DateCreate.ToString()), - new XElement("DateImplement", DateImplement.ToString())); - } + public OrderViewModel GetViewModel => new() + { + Id = Id, + ClientId = ClientId, + ImplementerId = ImplementerId, + ManufactureId = ManufactureId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; + + public XElement GetXElement => new("Order", + new XAttribute("Id", Id), + new XElement("ClientId", ClientId.ToString()), + new XElement("ImplementerId", ClientId.ToString()), + new XElement("ManufactureId", ManufactureId.ToString()), + new XElement("Count", Count.ToString()), + new XElement("Sum", Sum.ToString()), + new XElement("Status", Status.ToString()), + new XElement("DateCreate", DateCreate.ToString()), + new XElement("DateImplement", DateImplement.ToString())); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs index f5b148f..4ca4522 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs @@ -24,12 +24,16 @@ namespace BlacksmithWorkshopListImplement //список для хранения клиентов public List Clients { get; set; } + //список для хранения исполнителей + public List Implementers { get; set; } + public DataListSingleton() { WorkPieces = new List(); Manufactures = new List(); Orders = new List(); Clients = new List(); + Implementers = new List(); } public static DataListSingleton GetInstance() diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/ImplementerStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..33802be --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,130 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.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)) + { + 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) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) + { + return null; + } + + foreach (var implementer in _source.Implementers) + { + if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) || + (model.Id.HasValue && implementer.Id == model.Id)) + { + 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 (implementer.Id == model.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; + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/OrderStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/OrderStorage.cs index 63ccc7d..fa9540c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/OrderStorage.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/OrderStorage.cs @@ -11,178 +11,188 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopListImplement.Implements { - //класс, реализующий интерфейс хранилища заказов - public class OrderStorage : IOrderStorage - { - //поле для работы со списком заказов - private readonly DataListSingleton _source; + //класс, реализующий интерфейс хранилища заказов + public class OrderStorage : IOrderStorage + { + //поле для работы со списком заказов + private readonly DataListSingleton _source; - //получение в конструкторе объекта DataListSingleton - public OrderStorage() - { - _source = DataListSingleton.GetInstance(); - } + //получение в конструкторе объекта DataListSingleton + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } - //получение полного списка заготовок - public List GetFullList() - { - var result = new List(); + //получение полного списка заготовок + public List GetFullList() + { + var result = new List(); - foreach (var order in _source.Orders) - { - result.Add(GetViewModel(order)); - } + foreach (var order in _source.Orders) + { + result.Add(GetViewModel(order)); + } - return result; - } + return result; + } - //получение отфильтрованного списка заказов - public List GetFilteredList(OrderSearchModel model) - { - if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) - { - var result = new List(); + //получение отфильтрованного списка заказов + public List GetFilteredList(OrderSearchModel model) + { + if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) + { + var result = new List(); - foreach (var order in _source.Orders) - { - if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) - { - result.Add(GetViewModel(order)); - } - } + foreach (var order in _source.Orders) + { + if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) + { + result.Add(GetViewModel(order)); + } + } - return result; - } - else if (model.Id.HasValue) - { - foreach (var order in _source.Orders) - { - if (order.Id == model.Id) - { - return new() { GetViewModel(order) }; - } - } - } - else if (model.ClientId.HasValue) - { - var result = new List(); + return result; + } + else if (model.Id.HasValue) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + return new() { GetViewModel(order) }; + } + } + } + else if (model.ClientId.HasValue) + { + var result = new List(); - foreach (var order in _source.Orders) - { - if (order.ClientId == model.ClientId) - { - result.Add(GetViewModel(order)); - } - } + foreach (var order in _source.Orders) + { + if (order.ClientId == model.ClientId) + { + result.Add(GetViewModel(order)); + } + } - return result; - } + return result; + } - return new(); - } + return new(); + } - //получение элемента из списка заказов - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } + //получение элемента из списка заказов + 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 GetViewModel(order); - } - } + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + return GetViewModel(order); + } + } - return null; - } + return null; + } - //метод для записи названия изделия на форме с заказами - private OrderViewModel GetViewModel(Order order) - { - var viewModel = order.GetViewModel; + //метод для передачи названий и имён на форму + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; - foreach (var manufactures in _source.Manufactures) - { - if (manufactures.Id == order.ManufactureId) - { - viewModel.ManufactureName = manufactures.ManufactureName; + foreach (var manufactures in _source.Manufactures) + { + if (manufactures.Id == order.ManufactureId) + { + viewModel.ManufactureName = manufactures.ManufactureName; - break; - } - } + break; + } + } - foreach (var client in _source.Clients) - { - if (client.Id == order.ClientId) - { - viewModel.ClientFIO = client.ClientFIO; - break; - } - } + foreach (var client in _source.Clients) + { + if (client.Id == order.ClientId) + { + viewModel.ClientFIO = client.ClientFIO; + break; + } + } - return viewModel; - } + foreach (var implementer in _source.Implementers) + { + if (implementer.Id == order.ImplementerId) + { + viewModel.ImplementerFIO = implementer.ImplementerFIO; - //при создании заказа определяем для него новый id: ищем max id и прибавляем к нему 1 - public OrderViewModel? Insert(OrderBindingModel model) - { - model.Id = 1; + break; + } + } - foreach (var order in _source.Orders) - { - if (model.Id <= order.Id) - { - model.Id = order.Id + 1; - } - } + return viewModel; + } - var newOrder = Order.Create(model); + //при создании заказа определяем для него новый id: ищем max id и прибавляем к нему 1 + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = 1; - if (newOrder == null) - { - return null; - } + foreach (var order in _source.Orders) + { + if (model.Id <= order.Id) + { + model.Id = order.Id + 1; + } + } - _source.Orders.Add(newOrder); + var newOrder = Order.Create(model); - return GetViewModel(newOrder); - } + if (newOrder == null) + { + return null; + } - //обновление заказа - public OrderViewModel? Update(OrderBindingModel model) - { - foreach (var order in _source.Orders) - { - if (order.Id == model.Id) - { - order.Update(model); + _source.Orders.Add(newOrder); - return GetViewModel(order); - } - } + return GetViewModel(newOrder); + } - return null; - } + //обновление заказа + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); - //удаление заказа - 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 GetViewModel(order); + } + } - return GetViewModel(element); - } - } + return null; + } - 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 GetViewModel(element); + } + } + + return null; + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Implementer.cs new file mode 100644 index 0000000..4fc29a7 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Implementer.cs @@ -0,0 +1,67 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.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; } + + //метод для создания объекта от класса-компонента на основе класса-BindingModel + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Implementer() + { + Id = model.Id, + Password = model.Password, + ImplementerFIO = model.ImplementerFIO, + Qualification = model.Qualification, + WorkExperience = model.WorkExperience + }; + } + + //метод изменения существующего объекта + public void Update(ImplementerBindingModel? model) + { + if (model == null) + { + return; + } + + Password = model.Password; + ImplementerFIO = model.ImplementerFIO; + Qualification = model.Qualification; + WorkExperience = model.WorkExperience; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + ImplementerFIO = ImplementerFIO, + Qualification = Qualification, + WorkExperience = WorkExperience + }; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs index 2cfc89c..4d05c18 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs @@ -5,75 +5,80 @@ using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Reflection.PortableExecutable; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopListImplement.Models { - //класс, реализующий интерфейс модели заказа - public class Order : IOrderModel - { - //методы set сделали приватными, чтобы исключить неразрешённые манипуляции - public int Id { get; private set; } + //класс, реализующий интерфейс модели заказа + public class Order : IOrderModel + { + //методы set сделали приватными, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } - public int ClientId { get; private set; } + public int ClientId { get; private set; } - public int ManufactureId { get; private set; } + public int? ImplementerId { get; private set; } - public int Count { get; private set; } + public int ManufactureId { get; private set; } - public double Sum { get; private set; } + public int Count { get; private set; } - public OrderStatus Status { get; private set; } + public double Sum { get; private set; } - public DateTime DateCreate { get; private set; } = DateTime.Now; + public OrderStatus Status { get; private set; } - public DateTime? DateImplement { get; private set; } + public DateTime DateCreate { get; private set; } = DateTime.Now; - public static Order? Create(OrderBindingModel? model) - { - if (model == null) - { - return null; - } + public DateTime? DateImplement { get; private set; } - return new Order() - { - Id = model.Id, - ManufactureId = model.ManufactureId, - ClientId = model.ClientId, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; - } + public static Order? Create(OrderBindingModel? model) + { + if (model == null) + { + return null; + } - //метод изменения существующего объекта - public void Update(OrderBindingModel? model) - { - if (model == null) - { - return; - } + return new Order() + { + Id = model.Id, + ManufactureId = model.ManufactureId, + ClientId = model.ClientId, + ImplementerId = model.ImplementerId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } - Status = model.Status; - DateImplement = model.DateImplement; - } + //метод изменения существующего объекта + public void Update(OrderBindingModel? model) + { + if (model == null) + { + return; + } - //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента - public OrderViewModel GetViewModel => new() - { - Id = Id, - ManufactureId = ManufactureId, - ClientId = ClientId, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement - }; - } + Status = model.Status; + DateImplement = model.DateImplement; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public OrderViewModel GetViewModel => new() + { + Id = Id, + ManufactureId = ManufactureId, + ClientId = ClientId, + ImplementerId = ImplementerId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.Designer.cs new file mode 100644 index 0000000..f9fe0c2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.Designer.cs @@ -0,0 +1,164 @@ +using DocumentFormat.OpenXml.Wordprocessing; + +namespace BlacksmithWorkshop +{ + 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() + { + labelFIO = new Label(); + labelPassword = new Label(); + labelWorkExperience = new Label(); + labelQualification = new Label(); + textBoxImplementerFIO = new TextBox(); + textBoxPassword = new TextBox(); + textBoxWorkExperience = new TextBox(); + textBoxQualification = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + SuspendLayout(); + // + // labelFIO + // + labelFIO.AutoSize = true; + labelFIO.Location = new Point(38, 27); + labelFIO.Name = "labelFIO"; + labelFIO.Size = new Size(45, 20); + labelFIO.TabIndex = 0; + labelFIO.Text = "ФИО:"; + // + // labelPassword + // + labelPassword.AutoSize = true; + labelPassword.Location = new Point(38, 79); + labelPassword.Name = "labelPassword"; + labelPassword.Size = new Size(65, 20); + labelPassword.TabIndex = 1; + labelPassword.Text = "Пароль:"; + // + // labelWorkExperience + // + labelWorkExperience.AutoSize = true; + labelWorkExperience.Location = new Point(38, 136); + labelWorkExperience.Name = "labelWorkExperience"; + labelWorkExperience.Size = new Size(102, 20); + labelWorkExperience.TabIndex = 2; + labelWorkExperience.Text = "Стаж работы:"; + // + // labelQualification + // + labelQualification.AutoSize = true; + labelQualification.Location = new Point(319, 136); + labelQualification.Name = "labelQualification"; + labelQualification.Size = new Size(114, 20); + labelQualification.TabIndex = 3; + labelQualification.Text = "Квалификация:"; + // + // textBoxImplementerFIO + // + textBoxImplementerFIO.Location = new Point(160, 24); + textBoxImplementerFIO.Name = "textBoxImplementerFIO"; + textBoxImplementerFIO.Size = new Size(436, 27); + textBoxImplementerFIO.TabIndex = 4; + // + // textBoxPassword + // + textBoxPassword.Location = new Point(160, 76); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.Size = new Size(436, 27); + textBoxPassword.TabIndex = 5; + // + // textBoxWorkExperience + // + textBoxWorkExperience.Location = new Point(160, 133); + textBoxWorkExperience.Name = "textBoxWorkExperience"; + textBoxWorkExperience.Size = new Size(126, 27); + textBoxWorkExperience.TabIndex = 6; + // + // textBoxQualification + // + textBoxQualification.Location = new Point(444, 133); + textBoxQualification.Name = "textBoxQualification"; + textBoxQualification.Size = new Size(152, 27); + textBoxQualification.TabIndex = 7; + // + // buttonSave + // + buttonSave.Location = new Point(387, 178); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(94, 29); + buttonSave.TabIndex = 8; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(502, 178); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(94, 29); + buttonCancel.TabIndex = 9; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(662, 224); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxQualification); + Controls.Add(textBoxWorkExperience); + Controls.Add(textBoxPassword); + Controls.Add(textBoxImplementerFIO); + Controls.Add(labelQualification); + Controls.Add(labelWorkExperience); + Controls.Add(labelPassword); + Controls.Add(labelFIO); + Name = "FormImplementer"; + Text = "Исполнитель"; + Load += FormImplementer_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelFIO; + private Label labelPassword; + private Label labelWorkExperience; + private Label labelQualification; + private TextBox textBoxImplementerFIO; + private TextBox textBoxPassword; + private TextBox textBoxWorkExperience; + private TextBox textBoxQualification; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.cs new file mode 100644 index 0000000..fcbaf13 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.cs @@ -0,0 +1,138 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BlacksmithWorkshop +{ + 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) + { + //проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + + var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value }); + + if (view != null) + { + textBoxImplementerFIO.Text = view.ImplementerFIO; + textBoxPassword.Text = view.Password; + textBoxWorkExperience.Text = view.WorkExperience.ToString(); + textBoxQualification.Text = view.Qualification.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + //проверка на заполнение поля с ФИО исполнителя + if (string.IsNullOrEmpty(textBoxImplementerFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + //проверка на заполнение поля с паролем + if (string.IsNullOrEmpty(textBoxPassword.Text)) + { + MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + //проверка на заполнение поля со стажем + if (string.IsNullOrEmpty(textBoxWorkExperience.Text)) + { + MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + //проверка на заполнение поля с квалификацией + if (string.IsNullOrEmpty(textBoxQualification.Text)) + { + MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + _logger.LogInformation("Сохранение исполнителя"); + + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxImplementerFIO.Text, + Password = textBoxPassword.Text, + WorkExperience = Convert.ToInt16(textBoxWorkExperience.Text), + Qualification = Convert.ToInt16(textBoxQualification.Text) + }; + + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + + if (!operationResult) + { + throw new Exception("Ошибка при сохранеии. Дополнительная информация в логах."); + } + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения исполнителя"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementer.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/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/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.Designer.cs new file mode 100644 index 0000000..8aaf6d2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.Designer.cs @@ -0,0 +1,114 @@ +namespace BlacksmithWorkshop +{ + 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() + { + dataGridView = new DataGridView(); + buttonCreate = new Button(); + buttonChange = new Button(); + buttonDelete = new Button(); + buttonUpdate = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(768, 426); + dataGridView.TabIndex = 0; + // + // buttonCreate + // + buttonCreate.Location = new Point(805, 22); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(160, 29); + buttonCreate.TabIndex = 1; + buttonCreate.Text = "Создать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreate_Click; + // + // buttonChange + // + buttonChange.Location = new Point(805, 90); + buttonChange.Name = "buttonChange"; + buttonChange.Size = new Size(160, 29); + buttonChange.TabIndex = 2; + buttonChange.Text = "Изменить"; + buttonChange.UseVisualStyleBackColor = true; + buttonChange.Click += ButtonChange_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(805, 153); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(160, 29); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(805, 218); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(160, 29); + buttonUpdate.TabIndex = 4; + buttonUpdate.Text = "Обновить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonUpdate_Click; + // + // FormImplementers + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(991, 450); + Controls.Add(buttonUpdate); + Controls.Add(buttonDelete); + Controls.Add(buttonChange); + Controls.Add(buttonCreate); + Controls.Add(dataGridView); + Name = "FormImplementers"; + Text = "Исполнители"; + Load += FormImplementers_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonCreate; + private Button buttonChange; + private Button buttonDelete; + private Button buttonUpdate; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs new file mode 100644 index 0000000..46d0dbf --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs @@ -0,0 +1,127 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BlacksmithWorkshop +{ + 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); + + //растягиваем колонку Название на всю ширину, колонку Id скрываем + 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 ButtonCreate_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 ButtonChange_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 ButtonDelete_Click(object sender, EventArgs e) + { + //проверяем наличие выделенной строки + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + + _logger.LogInformation("Удаление исполнителя"); + + try + { + if (!_logic.Delete(new ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonUpdate_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/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