diff --git a/BlacksmithWorkshop/BlacksmithWorkshop.sln b/BlacksmithWorkshop/BlacksmithWorkshop.sln index e88ffda..9226f5b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop.sln +++ b/BlacksmithWorkshop/BlacksmithWorkshop.sln @@ -3,7 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32602.215 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopView", "BlacksmithWorkshopView\BlacksmithWorkshopView.csproj", "{BD3DEE88-9AE6-418F-8064-DEAED7BDD2F6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopView", "BlacksmithWorkshopView\BlacksmithWorkshopView.csproj", "{BD3DEE88-9AE6-418F-8064-DEAED7BDD2F6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopDataModels", "BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj", "{00786CC2-8E12-4924-81F4-AE936BB088A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopContracts", "BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj", "{0A1E6D90-7D57-4BA9-9D81-6980AC415C1D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopListImplement", "BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj", "{8A454829-6C94-4F27-9CC8-1127E0D04123}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopBusinessLogic", "BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj", "{5934B6B0-3EA1-4AA5-9A2D-144CDC7D4DB0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +23,22 @@ Global {BD3DEE88-9AE6-418F-8064-DEAED7BDD2F6}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD3DEE88-9AE6-418F-8064-DEAED7BDD2F6}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD3DEE88-9AE6-418F-8064-DEAED7BDD2F6}.Release|Any CPU.Build.0 = Release|Any CPU + {00786CC2-8E12-4924-81F4-AE936BB088A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {00786CC2-8E12-4924-81F4-AE936BB088A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {00786CC2-8E12-4924-81F4-AE936BB088A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {00786CC2-8E12-4924-81F4-AE936BB088A8}.Release|Any CPU.Build.0 = Release|Any CPU + {0A1E6D90-7D57-4BA9-9D81-6980AC415C1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A1E6D90-7D57-4BA9-9D81-6980AC415C1D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A1E6D90-7D57-4BA9-9D81-6980AC415C1D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A1E6D90-7D57-4BA9-9D81-6980AC415C1D}.Release|Any CPU.Build.0 = Release|Any CPU + {8A454829-6C94-4F27-9CC8-1127E0D04123}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8A454829-6C94-4F27-9CC8-1127E0D04123}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8A454829-6C94-4F27-9CC8-1127E0D04123}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8A454829-6C94-4F27-9CC8-1127E0D04123}.Release|Any CPU.Build.0 = Release|Any CPU + {5934B6B0-3EA1-4AA5-9A2D-144CDC7D4DB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5934B6B0-3EA1-4AA5-9A2D-144CDC7D4DB0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5934B6B0-3EA1-4AA5-9A2D-144CDC7D4DB0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5934B6B0-3EA1-4AA5-9A2D-144CDC7D4DB0}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj new file mode 100644 index 0000000..3eaaccd --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj @@ -0,0 +1,19 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ManufactureLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ManufactureLogic.cs new file mode 100644 index 0000000..113889f --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/ManufactureLogic.cs @@ -0,0 +1,160 @@ +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 ManufactureLogic : IManufactureLogic + { + private readonly ILogger _logger; + + private readonly IManufactureStorage _manufactureStorage; + + //конструктор + public ManufactureLogic(ILogger logger, IManufactureStorage manufactureStorage) + { + _logger = logger; + _manufactureStorage = manufactureStorage; + } + + //вывод отфильтрованного списка + public List? ReadList(ManufactureSearchModel? model) + { + _logger.LogInformation("ReadList. ManufactureName:{ManufactureName}. Id:{Id}", model?.ManufactureName, model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _manufactureStorage.GetFullList() : _manufactureStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + + return list; + } + + //вывод конкретного изделия + public ManufactureViewModel? ReadElement(ManufactureSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. ManufactureName:{ManufactureName}. Id:{Id}", model.ManufactureName, model.Id); + + var element = _manufactureStorage.GetElement(model); + + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + + return null; + } + + _logger.LogInformation("ReadElement find. Id:{Id}", model.Id); + + return element; + } + + //Создание изделия + public bool Create(ManufactureBindingModel model) + { + CheckModel(model); + + if (_manufactureStorage.Insert(model) == null) + { + _logger.LogWarning("Create operation failed"); + + return false; + } + + return true; + } + + //обновление изделия + public bool Update(ManufactureBindingModel model) + { + CheckModel(model); + + if (_manufactureStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + + return true; + } + + //удаление изделия + public bool Delete(ManufactureBindingModel model) + { + CheckModel(model, false); + + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_manufactureStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + + return false; + } + + return true; + } + + //проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(ManufactureBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении параметром withParams передаём false + if (!withParams) + { + return; + } + + //проверка на наличие названия изделия + if (string.IsNullOrEmpty(model.ManufactureName)) + { + throw new ArgumentNullException("Нет названия изделия", nameof(model.ManufactureName)); + } + + //проверка на наличие нормальной цены у изделия + if (model.Price <= 0) + { + throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price)); + } + + _logger.LogInformation("Manufacture. ManufactureName:{ManufactureName}. Price:{Price}. Id:{Id}", + model.ManufactureName, model.Price, model.Id); + + //проверка на наличие такого же изделия в списке + var element = _manufactureStorage.GetElement(new ManufactureSearchModel + { + ManufactureName = model.ManufactureName, + }); + + //если элемент найден и его 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 new file mode 100644 index 0000000..6ca58be --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -0,0 +1,173 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.BusinessLogic +{ + public class OrderLogic : IOrderLogic + { + private readonly ILogger _logger; + + private readonly IOrderStorage _orderStorage; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } + + //вывод отфильтрованного списка компонентов + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. Id:{Id}", model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + + return list; + } + + //создание чека + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + + if (model.Status != OrderStatus.Неизвестен) + { + _logger.LogWarning("Insert operation failed, incorrect order status"); + return false; + } + + model.Status = OrderStatus.Принят; + + if (_orderStorage.Insert(model) == null) + { + model.Status = OrderStatus.Неизвестен; + _logger.LogWarning("Insert operation failed"); + return false; + } + + return true; + } + + public bool TakeOrderInWork(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } + + public bool FinishOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Готов); + } + + public bool DeliveryOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выдан); + } + + //проверка на пустоту входного параметра + private void CheckModel(OrderBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении параметром withParams передаём false + if (!withParams) + { + return; + } + + //проверка на наличие товаров в заказе + if (model.Count <= 0) + { + throw new ArgumentNullException("В заказе не может быть 0 изделий", nameof(model.Count)); + } + + //проверка на наличие нормальной суммарной стоимости чека + if (model.Sum <= 0) + { + throw new ArgumentNullException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); + } + + //проверка корректности id у изделий + if (model.ManufactureId < 0) + { + throw new ArgumentNullException("Некорректный id у изделия", nameof(model.ManufactureId)); + } + + //проверка корректности дат + if (model.DateCreate > model.DateImplement) + { + throw new InvalidOperationException("Дата создания должна быть более ранней, нежели дата завершения"); + } + + _logger.LogInformation("Order. OrderId:{Id}. Sun:{Sum}. ManufactureId:{Id}", model.Id, model.Sum, model.ManufactureId); + } + + //обновление статуса заказа + public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus) + { + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + + //если не смогли найти указанный заказ по его Id + if (viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //проверка на возможность обновления статуса на следующий + if (viewModel.Status + 1 != newOrderStatus) + { + _logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect"); + return false; + } + + model.Status = newOrderStatus; + + //проверка на выдачу + 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/WorkPieceLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/WorkPieceLogic.cs new file mode 100644 index 0000000..1966b61 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogic/WorkPieceLogic.cs @@ -0,0 +1,161 @@ +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 WorkPieceLogic : IWorkPieceLogic + { + private readonly ILogger _logger; + + private readonly IWorkPieceStorage _workPieceStorage; + + //конструктор + public WorkPieceLogic(ILogger logger, IWorkPieceStorage workPieceStorage) + { + _logger = logger; + _workPieceStorage = workPieceStorage; + } + + //вывод отфильтрованного списка компонентов + public List? ReadList(WorkPieceSearchModel? model) + { + _logger.LogInformation("ReadList. WorkPieceName:{WorkPieceName}. Id:{Id}", model?.WorkPieceName, model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _workPieceStorage.GetFullList() : _workPieceStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + + return list; + } + + //вывод конкретного заготовки + public WorkPieceViewModel? ReadElement(WorkPieceSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. WorkPieceName:{WorkPieceName}. Id:{Id}", model.WorkPieceName, model.Id); + + var element = _workPieceStorage.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(WorkPieceBindingModel model) + { + CheckModel(model); + + if (_workPieceStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + + return false; + } + + return true; + } + + //обновление заготовки + public bool Update(WorkPieceBindingModel model) + { + CheckModel(model); + + if (_workPieceStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + + return false; + } + + return true; + } + + //удаление заготовки + public bool Delete(WorkPieceBindingModel model) + { + CheckModel(model, false); + + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_workPieceStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + + return false; + } + + return true; + } + + //проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(WorkPieceBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении передаём как параметр false + if (!withParams) + { + return; + } + + //проверка на наличие названия заготовки + if (string.IsNullOrEmpty(model.WorkPieceName)) + { + throw new ArgumentNullException("Нет названия заготовки", nameof(model.WorkPieceName)); + } + + //проверка на наличие нормальной цены у заготовки + if (model.Cost <= 0) + { + throw new ArgumentNullException("Цена заготовки должна быть больше 0", nameof(model.Cost)); + } + + _logger.LogInformation("WorkPiece. WorkPieceName:{WorkPieceName}. Cost:{Cost}. Id:{Id}", + model.WorkPieceName, model.Cost, model.Id); + + //проверка на наличие такой же заготовки в списке + var element = _workPieceStorage.GetElement(new WorkPieceSearchModel + { + WorkPieceName = model.WorkPieceName, + }); + + //если элемент найден и его Id не совпадает с Id переданного объекта + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Заготовка с таким названием уже есть"); + } + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/ManufactureBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/ManufactureBindingModel.cs new file mode 100644 index 0000000..40d055f --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/ManufactureBindingModel.cs @@ -0,0 +1,21 @@ +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BindingModels +{ + //реализация сущности "Изделие" + public class ManufactureBindingModel : IManufactureModel + { + public int Id { get; set; } + + public string ManufactureName { get; set; } = string.Empty; + + public double Price { get; set; } + + public Dictionary ManufactureWorkPieces { get; set; } = new(); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs new file mode 100644 index 0000000..5ab83dc --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/OrderBindingModel.cs @@ -0,0 +1,28 @@ +using BlacksmithWorkshopDataModels.Enums; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BindingModels +{ + //реализация сущности "Заказ" + public class OrderBindingModel : IOrderModel + { + public int Id { get; set; } + + public int ManufactureId { get; set; } + + public int Count { get; set; } + + public double Sum { get; set; } + + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + public DateTime DateCreate { get; set; } = DateTime.Now; + + public DateTime? DateImplement { get; set; } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/WorkPieceBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/WorkPieceBindingModel.cs new file mode 100644 index 0000000..6de90ac --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/WorkPieceBindingModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using BlacksmithWorkshopDataModels.Models; + +namespace BlacksmithWorkshopContracts.BindingModels +{ + //реализация сущности "Компонент" + public class WorkPieceBindingModel : IWorkPieceModel + { + public int Id { get; set; } + + public string WorkPieceName { get; set; } = string.Empty; + + public double Cost { get; set; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj new file mode 100644 index 0000000..f685e06 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IManufactureLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IManufactureLogic.cs new file mode 100644 index 0000000..b607c8d --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IManufactureLogic.cs @@ -0,0 +1,25 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + //бизнес-логика для продуктов + public interface IManufactureLogic + { + List? ReadList(ManufactureSearchModel? model); + + ManufactureViewModel? ReadElement(ManufactureSearchModel model); + + bool Create(ManufactureBindingModel model); + + bool Update(ManufactureBindingModel model); + + bool Delete(ManufactureBindingModel model); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs new file mode 100644 index 0000000..bf9c118 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -0,0 +1,25 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + //бизнес-логика для заказов + public interface IOrderLogic + { + List? ReadList(OrderSearchModel? model); + + bool CreateOrder(OrderBindingModel model); + + bool TakeOrderInWork(OrderBindingModel model); + + bool FinishOrder(OrderBindingModel model); + + bool DeliveryOrder(OrderBindingModel model); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IWorkPieceLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IWorkPieceLogic.cs new file mode 100644 index 0000000..8b77391 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IWorkPieceLogic.cs @@ -0,0 +1,25 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + //бизнес-логика для компонентов + public interface IWorkPieceLogic + { + List? ReadList(WorkPieceSearchModel? model); + + WorkPieceViewModel? ReadElement(WorkPieceSearchModel model); + + bool Create(WorkPieceBindingModel model); + + bool Update(WorkPieceBindingModel model); + + bool Delete(WorkPieceBindingModel model); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/ManufactureSearchModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/ManufactureSearchModel.cs new file mode 100644 index 0000000..f318c3b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/ManufactureSearchModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.SearchModels +{ + //модель для поиска заготовки "Продукт" (она же изделие) + public class ManufactureSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } + + //для поиска по названию + public string? ManufactureName { get; set; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs new file mode 100644 index 0000000..761ee8c --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/OrderSearchModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.SearchModels +{ + //для поиска сущности "Заказ" + public class OrderSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } + } + +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/WorkPieceSearchModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/WorkPieceSearchModel.cs new file mode 100644 index 0000000..03a0bd0 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/SearchModels/WorkPieceSearchModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.SearchModels +{ + //модель для поиска сущности "Компонент" (она же заготовка) + public class WorkPieceSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } + + //для поиска по названию + public string? WorkPieceName { get; set; } + } + +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IManufactureStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IManufactureStorage.cs new file mode 100644 index 0000000..181dd5a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IManufactureStorage.cs @@ -0,0 +1,27 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.StoragesContracts +{ + //класс для хранилища продуктов (изделий) + public interface IManufactureStorage + { + List GetFullList(); + + List GetFilteredList(ManufactureSearchModel model); + + ManufactureViewModel? GetElement(ManufactureSearchModel model); + + ManufactureViewModel? Insert(ManufactureBindingModel model); + + ManufactureViewModel? Update(ManufactureBindingModel model); + + ManufactureViewModel? Delete(ManufactureBindingModel model); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IOrderStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IOrderStorage.cs new file mode 100644 index 0000000..e075a33 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IOrderStorage.cs @@ -0,0 +1,27 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.StoragesContracts +{ + //класс для хранилища заказов + public interface IOrderStorage + { + List GetFullList(); + + List GetFilteredList(OrderSearchModel model); + + OrderViewModel? GetElement(OrderSearchModel model); + + OrderViewModel? Insert(OrderBindingModel model); + + OrderViewModel? Update(OrderBindingModel model); + + OrderViewModel? Delete(OrderBindingModel model); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IWorkPieceStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IWorkPieceStorage.cs new file mode 100644 index 0000000..57968e9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IWorkPieceStorage.cs @@ -0,0 +1,27 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.StoragesContracts +{ + //класс хранилища компонентов (заготовок) + public interface IWorkPieceStorage + { + List GetFullList(); + + List GetFilteredList(WorkPieceSearchModel model); + + WorkPieceViewModel? GetElement(WorkPieceSearchModel model); + + WorkPieceViewModel? Insert(WorkPieceBindingModel model); + + WorkPieceViewModel? Update(WorkPieceBindingModel model); + + WorkPieceViewModel? Delete(WorkPieceBindingModel model); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs new file mode 100644 index 0000000..9a4946f --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs @@ -0,0 +1,24 @@ +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.ViewModels +{ + //класс для отображения пользователю информаци о продуктах (изделиях) + public class ManufactureViewModel : IManufactureModel + { + public int Id { get; set; } + + [DisplayName("Навание изделия")] + public string ManufactureName { get; set; } = string.Empty; + + [DisplayName("Цена")] + public double Price { get; set; } + + public Dictionary ManufactureWorkPieces { get; set; } = new(); + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs new file mode 100644 index 0000000..83174ed --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs @@ -0,0 +1,38 @@ +using BlacksmithWorkshopDataModels.Enums; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.ViewModels +{ + //класс для отображения пользователю информации о заказах + public class OrderViewModel : IOrderModel + { + [DisplayName("Номер")] + public int Id { get; set; } + + public int ManufactureId { get; set; } + + [DisplayName("Изделие")] + public string ManufactureName { get; set; } = string.Empty; + + [DisplayName("Количество")] + public int Count { get; set; } + + [DisplayName("Сумма")] + public double Sum { get; set; } + + [DisplayName("Статус")] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + [DisplayName("Дата создания")] + public DateTime DateCreate { get; set; } = DateTime.Now; + + [DisplayName("Дата выполнения")] + public DateTime? DateImplement { get; set; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs new file mode 100644 index 0000000..17e1910 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/WorkPieceViewModel.cs @@ -0,0 +1,22 @@ +using BlacksmithWorkshopDataModels.Models; +using System.ComponentModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.ViewModels +{ + //класс для отображения пользователю данных о заготовких (заготовках) + public class WorkPieceViewModel : IWorkPieceModel + { + public int Id { get; set; } + + [DisplayName("Название заготовки")] + public string WorkPieceName { get; set; } = string.Empty; + + [DisplayName("Цена")] + public double Cost { get; set; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/BlacksmithWorkshopDataModels.csproj b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/BlacksmithWorkshopDataModels.csproj new file mode 100644 index 0000000..132c02c --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/BlacksmithWorkshopDataModels.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Enums/OrderStatus.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Enums/OrderStatus.cs new file mode 100644 index 0000000..293d304 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Enums/OrderStatus.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDataModels.Enums +{ + //статус заказа + public enum OrderStatus + { + Неизвестен = -1, + + Принят = 0, + + Выполняется = 1, + + Готов = 2, + + Выдан = 3 + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/IId.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/IId.cs new file mode 100644 index 0000000..1804a4a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/IId.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDataModels +{ + //интерфейс, отвечающий за id у компонентов, продуктов и чеков + public interface IId + { + int Id { get; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IManufactureModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IManufactureModel.cs new file mode 100644 index 0000000..e9ebbd6 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IManufactureModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDataModels.Models +{ + //интерфейс, отвечающий за продукт + public interface IManufactureModel : IId + { + //наименование изделия + string ManufactureName { get; } + + //цена изделия + double Price { get; } + + //словарь, хранящий пары кол-во + компонент и его цена + Dictionary ManufactureWorkPieces { get; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs new file mode 100644 index 0000000..1659421 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IOrderModel.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using BlacksmithWorkshopDataModels.Enums; + +namespace BlacksmithWorkshopDataModels.Models +{ + //интерфейс, отвечающий за заказ + public interface IOrderModel : IId + { + //id продукта + int ManufactureId { get; } + + //кол-во продуктов + int Count { get; } + + //суммарная стоимость продуктов + double Sum { get; } + + //статус заказа + OrderStatus Status { get; } + + //дата создания заказа + DateTime DateCreate { get; } + + //дата завершения заказа (не обязательна к указанию сразу) + DateTime? DateImplement { get; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IWorkPieceModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IWorkPieceModel.cs new file mode 100644 index 0000000..5250bef --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IWorkPieceModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDataModels.Models +{ + //интерфейс, отвечающий за компоненты + public interface IWorkPieceModel : IId + { + //название составляющей (изделие состоит из составляющих) + string WorkPieceName { get; } + + //цена составляющей + double Cost { get; } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj new file mode 100644 index 0000000..b65badc --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/BlacksmithWorkshopListImplement.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs new file mode 100644 index 0000000..9ee2626 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/DataListSingleton.cs @@ -0,0 +1,41 @@ +using BlacksmithWorkshopListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement +{ + //класс для списков, в которых будет храниться информация при работе приложения + public class DataListSingleton + { + private static DataListSingleton? _instance; + + //список для хранения заготовок + public List WorkPieces { get; set; } + + //список для хранения изделий + public List Manufactures { get; set; } + + //список для хранения заказов + public List Orders { get; set; } + + public DataListSingleton() + { + WorkPieces = new List(); + Manufactures = new List(); + Orders = new List(); + } + + public static DataListSingleton GetInstance() + { + if (_instance == null) + { + _instance = new DataListSingleton(); + } + + return _instance; + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/ManufactureStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/ManufactureStorage.cs new file mode 100644 index 0000000..ca795f1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/ManufactureStorage.cs @@ -0,0 +1,138 @@ +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 ManufactureStorage : IManufactureStorage + { + //поле для работы со списком изделий + private readonly DataListSingleton _source; + + //получение в конструкторе объекта DataListSingleton + public ManufactureStorage() + { + _source = DataListSingleton.GetInstance(); + } + + //получение полного списка изделий + public List GetFullList() + { + var result = new List(); + + foreach (var manufacture in _source.Manufactures) + { + result.Add(manufacture.GetViewModel); + } + + return result; + } + + //получение отфильтрованного списка изделий + public List GetFilteredList(ManufactureSearchModel model) + { + var result = new List(); + + if (string.IsNullOrEmpty(model.ManufactureName)) + { + return result; + } + + foreach (var manufacture in _source.Manufactures) + { + if (manufacture.ManufactureName.Contains(model.ManufactureName)) + { + result.Add(manufacture.GetViewModel); + } + } + + return result; + } + + //получение элемента из списка изделий + public ManufactureViewModel? GetElement(ManufactureSearchModel model) + { + if (string.IsNullOrEmpty(model.ManufactureName) && !model.Id.HasValue) + { + return null; + } + + foreach (var manufacture in _source.Manufactures) + { + if ((!string.IsNullOrEmpty(model.ManufactureName) && manufacture.ManufactureName == model.ManufactureName) || + (model.Id.HasValue && manufacture.Id == model.Id)) + { + return manufacture.GetViewModel; + } + } + + return null; + } + + //при создании изделия определяем для него новый id: ищем max id и прибавлляем к нему 1 + public ManufactureViewModel? Insert(ManufactureBindingModel model) + { + model.Id = 1; + + foreach (var manufacture in _source.Manufactures) + { + if (model.Id <= manufacture.Id) + { + model.Id = manufacture.Id + 1; + } + } + + var newManufacture = Manufacture.Create(model); + + if (newManufacture == null) + { + return null; + } + + _source.Manufactures.Add(newManufacture); + + return newManufacture.GetViewModel; + } + + //обновление изделия + public ManufactureViewModel? Update(ManufactureBindingModel model) + { + foreach (var manufacture in _source.Manufactures) + { + if (manufacture.Id == model.Id) + { + manufacture.Update(model); + + return manufacture.GetViewModel; + } + } + + return null; + } + + //удаление изделия + public ManufactureViewModel? Delete(ManufactureBindingModel model) + { + for (int i = 0; i < _source.Manufactures.Count; ++i) + { + if (_source.Manufactures[i].Id == model.Id) + { + var element = _source.Manufactures[i]; + _source.Manufactures.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 new file mode 100644 index 0000000..a69eac6 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/OrderStorage.cs @@ -0,0 +1,155 @@ +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 OrderStorage : IOrderStorage + { + //поле для работы со списком заказов + private readonly DataListSingleton _source; + + //получение в конструкторе объекта DataListSingleton + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + + //получение полного списка заготовок + public List GetFullList() + { + var result = new List(); + + foreach (var order in _source.Orders) + { + result.Add(GetViewModel(order)); + } + + return result; + } + + //получение отфильтрованного списка заказов + public List GetFilteredList(OrderSearchModel model) + { + var result = new List(); + + if (!model.Id.HasValue) + { + return result; + } + + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + result.Add(GetViewModel(order)); + } + } + + return result; + } + + //получение элемента из списка заказов + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + return GetViewModel(order); + } + } + + return null; + } + + //метод для записи названия изделия на форме с заказами + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; + + foreach (var manufactures in _source.Manufactures) + { + if (manufactures.Id == order.ManufactureId) + { + viewModel.ManufactureName = manufactures.ManufactureName; + + break; + } + } + + return viewModel; + } + + //при создании заказа определяем для него новый id: ищем max id и прибавляем к нему 1 + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = 1; + + foreach (var order in _source.Orders) + { + if (model.Id <= order.Id) + { + model.Id = order.Id + 1; + } + } + + var newOrder = Order.Create(model); + + if (newOrder == null) + { + return null; + } + + _source.Orders.Add(newOrder); + + return GetViewModel(newOrder); + } + + //обновление заказа + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); + + return GetViewModel(order); + } + } + + 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/Implements/WorkPieceStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/WorkPieceStorage.cs new file mode 100644 index 0000000..b028c57 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/WorkPieceStorage.cs @@ -0,0 +1,138 @@ +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 WorkPieceStorage : IWorkPieceStorage + { + //поле для работы со списком заготовок + private readonly DataListSingleton _source; + + //получение в конструкторе объекта DataListSingleton + public WorkPieceStorage() + { + _source = DataListSingleton.GetInstance(); + } + + //получение полного списка заготовок + public List GetFullList() + { + var result = new List(); + + foreach (var workPiece in _source.WorkPieces) + { + result.Add(workPiece.GetViewModel); + } + + return result; + } + + //получение отфильтрованного списка заготовок + public List GetFilteredList(WorkPieceSearchModel model) + { + var result = new List(); + + if (string.IsNullOrEmpty(model.WorkPieceName)) + { + return result; + } + + foreach (var workPiece in _source.WorkPieces) + { + if (workPiece.WorkPieceName.Contains(model.WorkPieceName)) + { + result.Add(workPiece.GetViewModel); + } + } + + return result; + } + + //получение элемента из списка заготовок + public WorkPieceViewModel? GetElement(WorkPieceSearchModel model) + { + if (string.IsNullOrEmpty(model.WorkPieceName) && !model.Id.HasValue) + { + return null; + } + + foreach (var workPiece in _source.WorkPieces) + { + if ((!string.IsNullOrEmpty(model.WorkPieceName) && workPiece.WorkPieceName == model.WorkPieceName) || + (model.Id.HasValue && workPiece.Id == model.Id)) + { + return workPiece.GetViewModel; + } + } + + return null; + } + + //при создании заготовки определяем для него новый id: ищем max id и прибавляем к нему 1 + public WorkPieceViewModel? Insert(WorkPieceBindingModel model) + { + model.Id = 1; + + foreach (var workPiece in _source.WorkPieces) + { + if (model.Id <= workPiece.Id) + { + model.Id = workPiece.Id + 1; + } + } + + var newWorkPiece = WorkPiece.Create(model); + + if (newWorkPiece == null) + { + return null; + } + + _source.WorkPieces.Add(newWorkPiece); + + return newWorkPiece.GetViewModel; + } + + //обновление заготовки + public WorkPieceViewModel? Update(WorkPieceBindingModel model) + { + foreach (var workPiece in _source.WorkPieces) + { + if (workPiece.Id == model.Id) + { + workPiece.Update(model); + + return workPiece.GetViewModel; + } + } + + return null; + } + + //удаление заготовки + public WorkPieceViewModel? Delete(WorkPieceBindingModel model) + { + for (int i = 0; i < _source.WorkPieces.Count; ++i) + { + if (_source.WorkPieces[i].Id == model.Id) + { + var element = _source.WorkPieces[i]; + _source.WorkPieces.RemoveAt(i); + + return element.GetViewModel; + } + } + + return null; + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Manufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Manufacture.cs new file mode 100644 index 0000000..712018a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Manufacture.cs @@ -0,0 +1,63 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.Models +{ + //класс реализующий интерфейс модели изделия + public class Manufacture : IManufactureModel + { + //методы set делаем приватным, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } + + public string ManufactureName { get; private set; } = string.Empty; + + public double Price { get; private set; } + + public Dictionary ManufactureWorkPieces { get; private set; } = new Dictionary(); + + //метод для создания объекта от класса-компонента на основе класса-BindingModel + public static Manufacture? Create(ManufactureBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Manufacture() + { + Id = model.Id, + ManufactureName = model.ManufactureName, + Price = model.Price, + ManufactureWorkPieces = model.ManufactureWorkPieces + }; + } + + //метод изменения существующего объекта + public void Update(ManufactureBindingModel? model) + { + if (model == null) + { + return; + } + + ManufactureName = model.ManufactureName; + Price = model.Price; + ManufactureWorkPieces = model.ManufactureWorkPieces; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public ManufactureViewModel GetViewModel => new() + { + Id = Id, + ManufactureName = ManufactureName, + Price = Price, + ManufactureWorkPieces = ManufactureWorkPieces + }; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs new file mode 100644 index 0000000..53d4b82 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Order.cs @@ -0,0 +1,74 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Enums; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +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 int ManufactureId { get; private set; } + + public int Count { get; private set; } + + public double Sum { get; private set; } + + public OrderStatus Status { get; private set; } + + public DateTime DateCreate { get; private set; } = DateTime.Now; + + public DateTime? DateImplement { get; private set; } + + public static Order? Create(OrderBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Order() + { + Id = model.Id, + ManufactureId = model.ManufactureId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } + + //метод изменения существующего объекта + public void Update(OrderBindingModel? model) + { + if (model == null) + { + return; + } + Status = model.Status; + DateImplement = model.DateImplement; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public OrderViewModel GetViewModel => new() + { + Id = Id, + ManufactureId = ManufactureId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/WorkPiece.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/WorkPiece.cs new file mode 100644 index 0000000..7da5eb3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/WorkPiece.cs @@ -0,0 +1,58 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.Models +{ + //реализация интерфейса модели заготовки + public class WorkPiece : IWorkPieceModel + { + //методы set делаем приватным, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } + + public string WorkPieceName { get; private set; } = string.Empty; + + public double Cost { get; private set; } + + //метод для создания объекта от класса-компонента на основе класса-BindingModel + public static WorkPiece? Create(WorkPieceBindingModel? model) + { + if (model == null) + { + return null; + } + + return new WorkPiece() + { + Id = model.Id, + WorkPieceName = model.WorkPieceName, + Cost = model.Cost + }; + } + + //метод изменения существующего объекта + public void Update(WorkPieceBindingModel? model) + { + if (model == null) + { + return; + } + + WorkPieceName = model.WorkPieceName; + Cost = model.Cost; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public WorkPieceViewModel GetViewModel => new() + { + Id = Id, + WorkPieceName = WorkPieceName, + Cost = Cost + }; + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/BlacksmithWorkshopView.csproj b/BlacksmithWorkshop/BlacksmithWorkshopView/BlacksmithWorkshopView.csproj index b57c89e..e0f7d3d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/BlacksmithWorkshopView.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/BlacksmithWorkshopView.csproj @@ -8,4 +8,17 @@ enable + + + + + + + + + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.Designer.cs deleted file mode 100644 index f7a7f4a..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.Designer.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace BlacksmithWorkshopView -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 450); - this.Text = "Form1"; - } - - #endregion - } -} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.cs deleted file mode 100644 index a09461b..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace BlacksmithWorkshopView -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.Designer.cs new file mode 100644 index 0000000..da2944a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.Designer.cs @@ -0,0 +1,144 @@ +namespace BlacksmithWorkshop +{ + partial class FormCreateOrder + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.labelManufacture = new System.Windows.Forms.Label(); + this.labelCount = new System.Windows.Forms.Label(); + this.labelSum = new System.Windows.Forms.Label(); + this.comboBoxManufacture = new System.Windows.Forms.ComboBox(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.textBoxSum = new System.Windows.Forms.TextBox(); + this.buttonSave = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // labelManufacture + // + this.labelManufacture.AutoSize = true; + this.labelManufacture.Location = new System.Drawing.Point(24, 24); + this.labelManufacture.Name = "labelManufacture"; + this.labelManufacture.Size = new System.Drawing.Size(71, 20); + this.labelManufacture.TabIndex = 0; + this.labelManufacture.Text = "Изделие:"; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(24, 70); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(93, 20); + this.labelCount.TabIndex = 1; + this.labelCount.Text = "Количество:"; + // + // labelSum + // + this.labelSum.AutoSize = true; + this.labelSum.Location = new System.Drawing.Point(24, 113); + this.labelSum.Name = "labelSum"; + this.labelSum.Size = new System.Drawing.Size(58, 20); + this.labelSum.TabIndex = 2; + this.labelSum.Text = "Сумма:"; + // + // comboBoxManufacture + // + this.comboBoxManufacture.FormattingEnabled = true; + this.comboBoxManufacture.Location = new System.Drawing.Point(166, 21); + this.comboBoxManufacture.Name = "comboBoxManufacture"; + this.comboBoxManufacture.Size = new System.Drawing.Size(278, 28); + this.comboBoxManufacture.TabIndex = 3; + this.comboBoxManufacture.SelectedIndexChanged += new System.EventHandler(this.ComboBoxManufacture_SelectedIndexChanged); + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(166, 67); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(278, 27); + this.textBoxCount.TabIndex = 4; + this.textBoxCount.TextChanged += new System.EventHandler(this.TextBoxCount_TextChanged); + // + // textBoxSum + // + this.textBoxSum.Location = new System.Drawing.Point(166, 110); + this.textBoxSum.Name = "textBoxSum"; + this.textBoxSum.Size = new System.Drawing.Size(278, 27); + this.textBoxSum.TabIndex = 5; + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(230, 155); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(94, 29); + this.buttonSave.TabIndex = 6; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(340, 155); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(94, 29); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // FormCreateOrder + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(479, 203); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.textBoxSum); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.comboBoxManufacture); + this.Controls.Add(this.labelSum); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.labelManufacture); + this.Name = "FormCreateOrder"; + this.Text = "Заказ"; + this.Load += new System.EventHandler(this.FormCreateOrder_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelManufacture; + private Label labelCount; + private Label labelSum; + private ComboBox comboBoxManufacture; + private TextBox textBoxCount; + private TextBox textBoxSum; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs new file mode 100644 index 0000000..631ce26 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs @@ -0,0 +1,146 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopDataModels.Models; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BlacksmithWorkshop +{ + public partial class FormCreateOrder : Form + { + private readonly ILogger _logger; + + private readonly IManufactureLogic _logicM; + + private readonly IOrderLogic _logicO; + + public FormCreateOrder(ILogger logger, IManufactureLogic logicM, IOrderLogic logicO) + { + InitializeComponent(); + + _logger = logger; + _logicM = logicM; + _logicO = logicO; + } + + private void FormCreateOrder_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий для заказа"); + + try + { + var list = _logicM.ReadList(null); + + if (list != null) + { + comboBoxManufacture.DisplayMember = "ManufactureName"; + comboBoxManufacture.ValueMember = "Id"; + comboBoxManufacture.DataSource = list; + comboBoxManufacture.SelectedItem = null; + } + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий для заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void CalcSum() + { + if (comboBoxManufacture.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) + { + try + { + int id = Convert.ToInt32(comboBoxManufacture.SelectedValue); + + var manufacture = _logicM.ReadElement(new ManufactureSearchModel + { + Id = id + }); + + int count = Convert.ToInt32(textBoxCount.Text); + + textBoxSum.Text = Math.Round(count * (manufacture?.Price ?? 0), 2).ToString(); + + _logger.LogInformation("Расчет суммы заказа"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка расчета суммы заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void TextBoxCount_TextChanged(object sender, EventArgs e) + { + CalcSum(); + } + + private void ComboBoxManufacture_SelectedIndexChanged(object sender, EventArgs e) + { + CalcSum(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (comboBoxManufacture.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + _logger.LogInformation("Создание заказа"); + + try + { + var operationResult = _logicO.CreateOrder(new OrderBindingModel + { + ManufactureId = Convert.ToInt32(comboBoxManufacture.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text), + Sum = Convert.ToDouble(textBoxSum.Text) + }); + + if (!operationResult) + { + throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах."); + } + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/Form1.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.resx similarity index 100% rename from BlacksmithWorkshop/BlacksmithWorkshopView/Form1.resx rename to BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.resx diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs new file mode 100644 index 0000000..018e907 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs @@ -0,0 +1,176 @@ +namespace BlacksmithWorkshop +{ + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.buttonCreateOrder = new System.Windows.Forms.Button(); + this.buttonTakeOrderInWork = new System.Windows.Forms.Button(); + this.buttonOrderReady = new System.Windows.Forms.Button(); + this.buttonIssuedOrder = new System.Windows.Forms.Button(); + this.buttonRef = new System.Windows.Forms.Button(); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.toolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.workPieceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.manufactureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.menuStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 36); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(937, 402); + this.dataGridView.TabIndex = 0; + // + // buttonCreateOrder + // + this.buttonCreateOrder.Location = new System.Drawing.Point(1014, 66); + this.buttonCreateOrder.Name = "buttonCreateOrder"; + this.buttonCreateOrder.Size = new System.Drawing.Size(235, 29); + this.buttonCreateOrder.TabIndex = 1; + this.buttonCreateOrder.Text = "Создать заказ"; + this.buttonCreateOrder.UseVisualStyleBackColor = true; + this.buttonCreateOrder.Click += new System.EventHandler(this.ButtonCreateOrder_Click); + // + // buttonTakeOrderInWork + // + this.buttonTakeOrderInWork.Location = new System.Drawing.Point(1014, 143); + this.buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + this.buttonTakeOrderInWork.Size = new System.Drawing.Size(235, 29); + this.buttonTakeOrderInWork.TabIndex = 2; + this.buttonTakeOrderInWork.Text = "Отдать на выполнение"; + this.buttonTakeOrderInWork.UseVisualStyleBackColor = true; + this.buttonTakeOrderInWork.Click += new System.EventHandler(this.ButtonTakeOrderInWork_Click); + // + // buttonOrderReady + // + this.buttonOrderReady.Location = new System.Drawing.Point(1014, 220); + this.buttonOrderReady.Name = "buttonOrderReady"; + this.buttonOrderReady.Size = new System.Drawing.Size(235, 29); + this.buttonOrderReady.TabIndex = 3; + this.buttonOrderReady.Text = "Заказ готов"; + this.buttonOrderReady.UseVisualStyleBackColor = true; + this.buttonOrderReady.Click += new System.EventHandler(this.ButtonOrderReady_Click); + // + // buttonIssuedOrder + // + this.buttonIssuedOrder.Location = new System.Drawing.Point(1014, 296); + this.buttonIssuedOrder.Name = "buttonIssuedOrder"; + this.buttonIssuedOrder.Size = new System.Drawing.Size(235, 29); + this.buttonIssuedOrder.TabIndex = 4; + this.buttonIssuedOrder.Text = "Заказ выдан"; + this.buttonIssuedOrder.UseVisualStyleBackColor = true; + this.buttonIssuedOrder.Click += new System.EventHandler(this.ButtonIssuedOrder_Click); + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(1014, 369); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(235, 29); + this.buttonRef.TabIndex = 5; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // menuStrip1 + // + this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(1297, 28); + this.menuStrip1.TabIndex = 6; + this.menuStrip1.Text = "menuStrip1"; + // + // toolStripMenuItem + // + this.toolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.workPieceToolStripMenuItem, + this.manufactureToolStripMenuItem}); + this.toolStripMenuItem.Name = "toolStripMenuItem"; + this.toolStripMenuItem.Size = new System.Drawing.Size(117, 24); + this.toolStripMenuItem.Text = "Справочники"; + // + // workPieceToolStripMenuItem + // + this.workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem"; + this.workPieceToolStripMenuItem.Size = new System.Drawing.Size(162, 26); + this.workPieceToolStripMenuItem.Text = "Заготовки"; + this.workPieceToolStripMenuItem.Click += new System.EventHandler(this.WorkPieceToolStripMenuItem_Click); + // + // manufactureToolStripMenuItem + // + this.manufactureToolStripMenuItem.Name = "manufactureToolStripMenuItem"; + this.manufactureToolStripMenuItem.Size = new System.Drawing.Size(162, 26); + this.manufactureToolStripMenuItem.Text = "Изделия"; + this.manufactureToolStripMenuItem.Click += new System.EventHandler(this.ManufactureToolStripMenuItem_Click); + // + // FormMain + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1297, 450); + this.Controls.Add(this.buttonRef); + this.Controls.Add(this.buttonIssuedOrder); + this.Controls.Add(this.buttonOrderReady); + this.Controls.Add(this.buttonTakeOrderInWork); + this.Controls.Add(this.buttonCreateOrder); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.menuStrip1); + this.MainMenuStrip = this.menuStrip1; + this.Name = "FormMain"; + this.Text = "Кузнечная мастерская"; + this.Load += new System.EventHandler(this.FormMain_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private DataGridView dataGridView; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonIssuedOrder; + private Button buttonRef; + private MenuStrip menuStrip1; + private ToolStripMenuItem toolStripMenuItem; + private ToolStripMenuItem workPieceToolStripMenuItem; + private ToolStripMenuItem manufactureToolStripMenuItem; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs new file mode 100644 index 0000000..879038a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs @@ -0,0 +1,185 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopDataModels.Enums; +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 FormMain : Form + { + private readonly ILogger _logger; + + private readonly IOrderLogic _orderLogic; + + public FormMain(ILogger logger, IOrderLogic orderLogic) + { + InitializeComponent(); + + _logger = logger; + _orderLogic = orderLogic; + } + + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + + try + { + var list = _orderLogic.ReadList(null); + + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ManufactureId"].Visible = false; + } + + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormWorkPieces)); + + if (service is FormWorkPieces form) + { + form.ShowDialog(); + } + } + + private void ManufactureToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormManufactures)); + + if (service is FormManufactures form) + { + form.ShowDialog(); + } + } + + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + + } + + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id + }); + + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id + }); + + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); + + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + + _logger.LogInformation("Заказ №{id} выдан", id); + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.resx new file mode 100644 index 0000000..05252e7 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.resx @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 25 + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.Designer.cs new file mode 100644 index 0000000..916f3d3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.Designer.cs @@ -0,0 +1,232 @@ +namespace BlacksmithWorkshop +{ + partial class FormManufacture + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.labelName = new System.Windows.Forms.Label(); + this.labelCost = new System.Windows.Forms.Label(); + this.textBoxName = new System.Windows.Forms.TextBox(); + this.textBoxPrice = new System.Windows.Forms.TextBox(); + this.groupBoxWorkPiece = new System.Windows.Forms.GroupBox(); + this.buttonRef = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.buttonSave = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.ColumnID = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnPrice = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.groupBoxWorkPiece.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(23, 30); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(80, 20); + this.labelName.TabIndex = 0; + this.labelName.Text = "Название:"; + // + // labelCost + // + this.labelCost.AutoSize = true; + this.labelCost.Location = new System.Drawing.Point(23, 84); + this.labelCost.Name = "labelCost"; + this.labelCost.Size = new System.Drawing.Size(86, 20); + this.labelCost.TabIndex = 1; + this.labelCost.Text = "Стоимость:"; + // + // textBoxName + // + this.textBoxName.Location = new System.Drawing.Point(133, 27); + this.textBoxName.Name = "textBoxName"; + this.textBoxName.Size = new System.Drawing.Size(332, 27); + this.textBoxName.TabIndex = 2; + // + // textBoxPrice + // + this.textBoxPrice.Location = new System.Drawing.Point(133, 81); + this.textBoxPrice.Name = "textBoxPrice"; + this.textBoxPrice.Size = new System.Drawing.Size(196, 27); + this.textBoxPrice.TabIndex = 3; + // + // groupBoxWorkPiece + // + this.groupBoxWorkPiece.Controls.Add(this.buttonRef); + this.groupBoxWorkPiece.Controls.Add(this.buttonDel); + this.groupBoxWorkPiece.Controls.Add(this.buttonUpd); + this.groupBoxWorkPiece.Controls.Add(this.buttonAdd); + this.groupBoxWorkPiece.Controls.Add(this.dataGridView); + this.groupBoxWorkPiece.Location = new System.Drawing.Point(23, 126); + this.groupBoxWorkPiece.Name = "groupBoxWorkPiece"; + this.groupBoxWorkPiece.Size = new System.Drawing.Size(567, 300); + this.groupBoxWorkPiece.TabIndex = 4; + this.groupBoxWorkPiece.TabStop = false; + this.groupBoxWorkPiece.Text = "Заготовки"; + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(454, 196); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(94, 29); + this.buttonRef.TabIndex = 4; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(454, 145); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(94, 29); + this.buttonDel.TabIndex = 3; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(454, 95); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(94, 29); + this.buttonUpd.TabIndex = 2; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(454, 43); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(94, 29); + this.buttonAdd.TabIndex = 1; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.ColumnID, + this.ColumnName, + this.ColumnPrice}); + this.dataGridView.Location = new System.Drawing.Point(6, 26); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(436, 268); + this.dataGridView.TabIndex = 0; + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(340, 448); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(95, 29); + this.buttonSave.TabIndex = 5; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(458, 448); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(94, 29); + this.buttonCancel.TabIndex = 6; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // ColumnID + // + this.ColumnID.HeaderText = "Id"; + this.ColumnID.MinimumWidth = 6; + this.ColumnID.Name = "ColumnID"; + this.ColumnID.Visible = false; + this.ColumnID.Width = 125; + // + // ColumnName + // + this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; + this.ColumnName.HeaderText = "Название"; + this.ColumnName.MinimumWidth = 6; + this.ColumnName.Name = "ColumnName"; + // + // ColumnPrice + // + this.ColumnPrice.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; + this.ColumnPrice.HeaderText = "Количество"; + this.ColumnPrice.MinimumWidth = 6; + this.ColumnPrice.Name = "ColumnPrice"; + // + // FormManufacture + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(619, 500); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.groupBoxWorkPiece); + this.Controls.Add(this.textBoxPrice); + this.Controls.Add(this.textBoxName); + this.Controls.Add(this.labelCost); + this.Controls.Add(this.labelName); + this.Name = "FormManufacture"; + this.Text = "Изделие"; + this.Load += new System.EventHandler(this.FormManufacture_Load); + this.groupBoxWorkPiece.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelName; + private Label labelCost; + private TextBox textBoxName; + private TextBox textBoxPrice; + private GroupBox groupBoxWorkPiece; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + private Button buttonSave; + private Button buttonCancel; + private DataGridViewTextBoxColumn ColumnID; + private DataGridViewTextBoxColumn ColumnName; + private DataGridViewTextBoxColumn ColumnPrice; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs new file mode 100644 index 0000000..eef23ce --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs @@ -0,0 +1,246 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopDataModels.Models; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BlacksmithWorkshop +{ + public partial class FormManufacture : Form + { + private readonly ILogger _logger; + + private readonly IManufactureLogic _logic; + + private int? _id; + + private Dictionary _manufactureWorkPieces; + + public int Id { set { _id = value; } } + + public FormManufacture(ILogger logger, IManufactureLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + _manufactureWorkPieces = new Dictionary(); + } + + private void FormManufacture_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка изделия"); + + try + { + var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value }); + + if (view != null) + { + textBoxName.Text = view.ManufactureName; + textBoxPrice.Text = view.Price.ToString(); + _manufactureWorkPieces = view.ManufactureWorkPieces ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка заготовок для изделия"); + + try + { + if (_manufactureWorkPieces != null) + { + dataGridView.Rows.Clear(); + + foreach (var awp in _manufactureWorkPieces) + { + dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.WorkPieceName, awp.Value.Item2 }); + } + + textBoxPrice.Text = CalcPrice().ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заготовки для изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece)); + + if (service is FormManufactureWorkPiece form) + { + if (form.ShowDialog() == DialogResult.OK) + { + if (form.WorkPieceModel == null) + { + return; + } + + _logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); + + if (_manufactureWorkPieces.ContainsKey(form.Id)) + { + _manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); + } + else + { + _manufactureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count)); + } + + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece)); + + if (service is FormManufactureWorkPiece form) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _manufactureWorkPieces[id].Item2; + + if (form.ShowDialog() == DialogResult.OK) + { + if (form.WorkPieceModel == null) + { + return; + } + + _logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); + _manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); + + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + try + { + _logger.LogInformation("Удаление заготовки:{WorkPieceName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _manufactureWorkPieces?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + LoadData(); + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (_manufactureWorkPieces == null || _manufactureWorkPieces.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + _logger.LogInformation("Сохранение изделия"); + + try + { + var model = new ManufactureBindingModel + { + Id = _id ?? 0, + ManufactureName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + ManufactureWorkPieces = _manufactureWorkPieces + }; + + 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(); + } + + //в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%) + private double CalcPrice() + { + double price = 0; + + foreach (var elem in _manufactureWorkPieces) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } + + return Math.Round(price * 1.1, 2); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.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/FormManufactureWorkPiece.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.Designer.cs new file mode 100644 index 0000000..82b10ad --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.Designer.cs @@ -0,0 +1,119 @@ +namespace BlacksmithWorkshop +{ + partial class FormManufactureWorkPiece + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.labelWorkPiece = new System.Windows.Forms.Label(); + this.labelCount = new System.Windows.Forms.Label(); + this.comboBoxWorkPiece = new System.Windows.Forms.ComboBox(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.buttonSave = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // labelWorkPiece + // + this.labelWorkPiece.AutoSize = true; + this.labelWorkPiece.Location = new System.Drawing.Point(31, 33); + this.labelWorkPiece.Name = "labelWorkPiece"; + this.labelWorkPiece.Size = new System.Drawing.Size(81, 20); + this.labelWorkPiece.TabIndex = 0; + this.labelWorkPiece.Text = "Заготовка:"; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(31, 79); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(93, 20); + this.labelCount.TabIndex = 1; + this.labelCount.Text = "Количество:"; + // + // comboBoxWorkPiece + // + this.comboBoxWorkPiece.FormattingEnabled = true; + this.comboBoxWorkPiece.Location = new System.Drawing.Point(156, 30); + this.comboBoxWorkPiece.Name = "comboBoxWorkPiece"; + this.comboBoxWorkPiece.Size = new System.Drawing.Size(320, 28); + this.comboBoxWorkPiece.TabIndex = 2; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(156, 76); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(320, 27); + this.textBoxCount.TabIndex = 3; + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(235, 118); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(94, 29); + this.buttonSave.TabIndex = 4; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(353, 118); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(94, 29); + this.buttonCancel.TabIndex = 5; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // FormManufactureWorkPiece + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(526, 168); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.comboBoxWorkPiece); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.labelWorkPiece); + this.Name = "FormManufactureWorkPiece"; + this.Text = "Заготовки для изделия"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelWorkPiece; + private Label labelCount; + private ComboBox comboBoxWorkPiece; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.cs new file mode 100644 index 0000000..2af81d2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.cs @@ -0,0 +1,98 @@ +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Reflection.Metadata.Ecma335; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BlacksmithWorkshop +{ + public partial class FormManufactureWorkPiece : Form + { + private readonly List? _list; + + public int Id + { + get { return Convert.ToInt32(comboBoxWorkPiece.SelectedValue); } + set { comboBoxWorkPiece.SelectedValue = value; } + } + + public IWorkPieceModel? WorkPieceModel + { + get + { + if (_list == null) + { + return null; + } + + foreach (var elem in _list) + { + if (elem.Id == Id) + { + return elem; + } + } + + return null; + } + } + + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set + { + textBoxCount.Text = value.ToString(); + } + } + + public FormManufactureWorkPiece(IWorkPieceLogic logic) + { + InitializeComponent(); + + _list = logic.ReadList(null); + + if (_list != null) + { + comboBoxWorkPiece.DisplayMember = "WorkPieceName"; + comboBoxWorkPiece.ValueMember = "Id"; + comboBoxWorkPiece.DataSource = _list; + comboBoxWorkPiece.SelectedItem = null; + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (comboBoxWorkPiece.SelectedValue == null) + { + MessageBox.Show("Выберите заготовку", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + DialogResult = DialogResult.OK; + Close(); + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactureWorkPiece.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/FormManufactures.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.Designer.cs new file mode 100644 index 0000000..010505c --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.Designer.cs @@ -0,0 +1,115 @@ +namespace BlacksmithWorkshop +{ + partial class FormManufactures + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonAdd = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonDelete = new System.Windows.Forms.Button(); + this.buttonRef = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(653, 36); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(94, 29); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(653, 92); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(94, 29); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonDelete + // + this.buttonDelete.Location = new System.Drawing.Point(653, 151); + this.buttonDelete.Name = "buttonDelete"; + this.buttonDelete.Size = new System.Drawing.Size(94, 29); + this.buttonDelete.TabIndex = 2; + this.buttonDelete.Text = "Удалить"; + this.buttonDelete.UseVisualStyleBackColor = true; + this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click); + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(653, 203); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(94, 29); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(604, 426); + this.dataGridView.TabIndex = 4; + // + // FormManufactures + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(781, 450); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.buttonRef); + this.Controls.Add(this.buttonDelete); + this.Controls.Add(this.buttonUpd); + this.Controls.Add(this.buttonAdd); + this.Name = "FormManufactures"; + this.Text = "Изделия"; + this.Load += new System.EventHandler(this.FormManufactures_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button buttonAdd; + private Button buttonUpd; + private Button buttonDelete; + private Button buttonRef; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs new file mode 100644 index 0000000..54191d9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.cs @@ -0,0 +1,126 @@ +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 FormManufactures : Form + { + private readonly ILogger _logger; + + private readonly IManufactureLogic _logic; + + public FormManufactures(ILogger logger, IManufactureLogic logic) + { + + InitializeComponent(); + + _logger = logger; + _logic = logic; + } + + private void FormManufactures_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ManufactureWorkPieces"].Visible = false; + dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + + _logger.LogInformation("Загрузка изделий"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormManufacture)); + + if (service is FormManufacture form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormManufacture)); + + if (service is FormManufacture 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 ManufactureBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufactures.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/FormWorkPiece.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.Designer.cs new file mode 100644 index 0000000..c508b2a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.Designer.cs @@ -0,0 +1,119 @@ +namespace BlacksmithWorkshop +{ + partial class FormWorkPiece + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.labelName = new System.Windows.Forms.Label(); + this.labelPrice = new System.Windows.Forms.Label(); + this.textBoxName = new System.Windows.Forms.TextBox(); + this.textBoxCost = new System.Windows.Forms.TextBox(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(30, 24); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(80, 20); + this.labelName.TabIndex = 0; + this.labelName.Text = "Название:"; + // + // labelPrice + // + this.labelPrice.AutoSize = true; + this.labelPrice.Location = new System.Drawing.Point(30, 65); + this.labelPrice.Name = "labelPrice"; + this.labelPrice.Size = new System.Drawing.Size(48, 20); + this.labelPrice.TabIndex = 1; + this.labelPrice.Text = "Цена:"; + // + // textBoxName + // + this.textBoxName.Location = new System.Drawing.Point(127, 21); + this.textBoxName.Name = "textBoxName"; + this.textBoxName.Size = new System.Drawing.Size(293, 27); + this.textBoxName.TabIndex = 2; + // + // textBoxCost + // + this.textBoxCost.Location = new System.Drawing.Point(127, 62); + this.textBoxCost.Name = "textBoxCost"; + this.textBoxCost.Size = new System.Drawing.Size(179, 27); + this.textBoxCost.TabIndex = 3; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(326, 104); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(94, 29); + this.buttonCancel.TabIndex = 4; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(212, 104); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(94, 29); + this.buttonSave.TabIndex = 5; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // FormWorkPiece + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(464, 153); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxCost); + this.Controls.Add(this.textBoxName); + this.Controls.Add(this.labelPrice); + this.Controls.Add(this.labelName); + this.Name = "FormWorkPiece"; + this.Text = "Заготовка"; + this.Load += new System.EventHandler(this.FormWorkPiece_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelName; + private Label labelPrice; + private TextBox textBoxName; + private TextBox textBoxCost; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.cs new file mode 100644 index 0000000..a93fdd3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.cs @@ -0,0 +1,104 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using Microsoft.Extensions.Logging; + +namespace BlacksmithWorkshop +{ + //ôîðìà "Çàãîòîâêà" + public partial class FormWorkPiece : Form + { + private readonly ILogger _logger; + + private readonly IWorkPieceLogic _logic; + + private int? _id; + + public int Id { set { _id = value; } } + + //êîíñòðóêòîð + public FormWorkPiece(ILogger logger, IWorkPieceLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + } + + //ïðè çàãðóçêå ôîðìû + private void FormWorkPiece_Load(object sender, EventArgs e) + { + //ïðîâåðêà íà çàïîëíåíèå ïîëÿ id. Åñëè îíî çàïîëíåíî, òî ïðîáóåì ïîëó÷èòü çàïèñü è âûåñòè å¸ íà ýêðàí + if (_id.HasValue) + { + try + { + _logger.LogInformation("Ïîëó÷åíèå çàãîòîâêè"); + + var view = _logic.ReadElement(new WorkPieceSearchModel { Id = _id.Value }); + + if (view != null) + { + textBoxName.Text = view.WorkPieceName; + textBoxCost.Text = view.Cost.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Îøèáêà ïîëó÷åíèÿ êîìïîíåíòà"); + + MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + //îáðàáîòêà íàæàòèÿ êíîïêè Ñîõðàíèòü. Ëèáî ïååðäà¸ò äàííûå äëÿ ñîçäàíèÿ çàãîòîâêè, ëèáî å¸ îáíîâëåíèÿ + private void ButtonSave_Click(object sender, EventArgs e) + { + //ïðîâåðêà íà çàïîëíåíèå ïîëÿ ñ íàçâàíèåì çàãîòîâêè + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Çàïîëíèòå íàçâàíèå", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + _logger.LogInformation("Ñîõðàíåíèå çàãîòîâêè"); + + try + { + var model = new WorkPieceBindingModel + { + Id = _id ?? 0, + WorkPieceName = textBoxName.Text, + Cost = Convert.ToDouble(textBoxCost.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/FormWorkPiece.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPiece.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/FormWorkPieces.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.Designer.cs new file mode 100644 index 0000000..be21959 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.Designer.cs @@ -0,0 +1,115 @@ +namespace BlacksmithWorkshop +{ + partial class FormWorkPieces + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonAdd = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonDelete = new System.Windows.Forms.Button(); + this.buttonRef = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(653, 36); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(94, 29); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(653, 92); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(94, 29); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonDelete + // + this.buttonDelete.Location = new System.Drawing.Point(653, 151); + this.buttonDelete.Name = "buttonDelete"; + this.buttonDelete.Size = new System.Drawing.Size(94, 29); + this.buttonDelete.TabIndex = 2; + this.buttonDelete.Text = "Удалить"; + this.buttonDelete.UseVisualStyleBackColor = true; + this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click); + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(653, 203); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(94, 29); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(604, 426); + this.dataGridView.TabIndex = 4; + // + // FormWorkPieces + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(781, 450); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.buttonRef); + this.Controls.Add(this.buttonDelete); + this.Controls.Add(this.buttonUpd); + this.Controls.Add(this.buttonAdd); + this.Name = "FormWorkPieces"; + this.Text = "Заготовки"; + this.Load += new System.EventHandler(this.FormWorkPiece_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button buttonAdd; + private Button buttonUpd; + private Button buttonDelete; + private Button buttonRef; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs new file mode 100644 index 0000000..6bc847c --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.cs @@ -0,0 +1,126 @@ +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 FormWorkPieces : Form + { + private readonly ILogger _logger; + + private readonly IWorkPieceLogic _logic; + + public FormWorkPieces(ILogger logger, IWorkPieceLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormWorkPiece_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["WorkPieceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + + _logger.LogInformation("Загрузка заготовок"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заготовок"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); + + if (service is FormWorkPiece form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + //проверяем наличие выделенной строки + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); + + if (service is FormWorkPiece 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 WorkPieceBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.resx b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormWorkPieces.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/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs index 26b2cb6..b6b3059 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs @@ -1,17 +1,55 @@ -namespace BlacksmithWorkshopView +using BlacksmithWorkshopBusinessLogic.BusinessLogic; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopListImplement.Implements; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +namespace BlacksmithWorkshop { internal static class Program { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, + // To customize application configuration such as set high DPI settings or default font; // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + var services = new ServiceCollection(); + ConfigureServices(services); + _serviceProvider = services.BuildServiceProvider(); + Application.Run(_serviceProvider.GetRequiredService()); } + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + } } \ No newline at end of file