diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ComputerLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ComputerLogic.cs index 75d2a93..3c77dda 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ComputerLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ComputerLogic.cs @@ -15,43 +15,78 @@ namespace ComputersShopBusinessLogic.BusinessLogics public class ComputerLogic : IComputerLogic { private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем изделий + /// private readonly IComputerStorage _computerStorage; + + /// + /// Конструктор + /// + /// + /// public ComputerLogic(ILogger logger, IComputerStorage computerStorage) { _logger = logger; _computerStorage = computerStorage; } + + /// + /// Получение списка + /// + /// + /// public List? ReadList(ComputerSearchModel? model) { - _logger.LogInformation("ReadList. ComputerName:{ComputerName}. Id:{Id}", model?.ComputerName, model?.Id); + _logger.LogInformation("ReadList. ComputerName:{ComputerName}.Id:{ Id}", model?.ComputerName, model?.Id); + var list = model == null ? _computerStorage.GetFullList() : _computerStorage.GetFiltredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); return null; } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } + + /// + /// Получение отдельной записи + /// + /// + /// + /// public ComputerViewModel? ReadElement(ComputerSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. ComputerName:{ComputerName}. Id:{Id}", model.ComputerName, model.Id); + + _logger.LogInformation("ReadElement. ComputerName:{ComputerName}.Id:{ Id}", model.ComputerName, model.Id); + var element = _computerStorage.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(ComputerBindingModel model) { CheckModel(model); + if (_computerStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); @@ -59,9 +94,16 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + + /// + /// Изменение записи + /// + /// + /// public bool Update(ComputerBindingModel model) { CheckModel(model); + if (_computerStorage.Update(model) == null) { _logger.LogWarning("Update operation failed"); @@ -69,10 +111,17 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + + /// + /// Удаление записи + /// + /// + /// public bool Delete(ComputerBindingModel model) { CheckModel(model, false); _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_computerStorage.Delete(model) == null) { _logger.LogWarning("Delete operation failed"); @@ -80,6 +129,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + + /// + /// Проверка модели изделия + /// + /// + /// private void CheckModel(ComputerBindingModel model, bool withParams = true) { if (model == null) @@ -92,20 +147,20 @@ namespace ComputersShopBusinessLogic.BusinessLogics } if (string.IsNullOrEmpty(model.ComputerName)) { - throw new ArgumentNullException("Нет названия компьютера", nameof(model.ComputerName)); + throw new ArgumentNullException("Нет названия изделия", nameof(model.ComputerName)); } if (model.Price <= 0) { - throw new ArgumentNullException("Цена должна быть больше 0", nameof(model.Price)); + throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price)); } - _logger.LogInformation("Computer. ComputerName:{ComputerName}. Cost:{Cost}. Id:{Id}", model.ComputerName, model.Price, model.Id); + _logger.LogInformation("Computer. ComputerName:{ComputerName}.Price:{ Price}. Id: { Id}", model.ComputerName, model.Price, model.Id); var element = _computerStorage.GetElement(new ComputerSearchModel { ComputerName = model.ComputerName }); if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("Компьютер с таким названием уже есть"); + throw new InvalidOperationException("Изделие с таким названием уже есть"); } } } diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs index b21f70a..37e534f 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -9,6 +9,7 @@ using ComputersShopContracts.SearchModels; using ComputersShopContracts.StoragesContracts; using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Enums; +using ComputersShopDataModels.Models; using Microsoft.Extensions.Logging; namespace ComputersShopBusinessLogic.BusinessLogics @@ -16,33 +17,77 @@ namespace ComputersShopBusinessLogic.BusinessLogics public class OrderLogic : IOrderLogic { private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем заказов + /// private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + + /// + /// Взаимодействие с хранилищем магазинов + /// + private IShopStorage _shopStorage; + + /// + /// Бизнес-логика магазинов + /// + private IShopLogic _shopLogic; + + /// + /// Взаимодействие с хранилищем изделий + /// + private IComputerStorage _computerStorage; + + /// + /// Конструктор + /// + /// + /// + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IComputerStorage computerStorage) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; + _shopLogic = shopLogic; + _computerStorage = computerStorage; } + + /// + /// Получение списка + /// + /// + /// public List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. Id:{Id}", model?.Id); - var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFiltredList(model); + _logger.LogInformation("ReadList. Order.Id:{ Id}", model?.Id); + + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); return null; } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } + + /// + /// Создание заказа + /// + /// + /// public bool CreateOrder(OrderBindingModel model) { CheckModel(model); if (model.Status != OrderStatus.Неизвестен) { - _logger.LogWarning("Wrong order status. Insert operation failed"); + _logger.LogWarning("Insert operation failed. Order status incorrect."); return false; } + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); @@ -50,52 +95,42 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } - public bool ChangeStatus(OrderBindingModel model, OrderStatus newStatus) - { - var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (viewModel == null) - { - throw new ArgumentNullException(nameof(viewModel)); - } - if (viewModel.Status + 1 != newStatus) - { - _logger.LogWarning("Status change operation failed"); - return false; - } - model.Status = newStatus; - model.ComputerId = viewModel.ComputerId; - model.Count = viewModel.Count; - model.Sum = viewModel.Sum; - model.DateCreate = viewModel.DateCreate; - if (model.Status == OrderStatus.Готов) - { - model.DateImplement = DateTime.Now; - } - else - { - model.DateImplement = viewModel.DateImplement; - } - CheckModel(model, false); - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Status change operation failed"); - return false; - } - return true; - } + /// + /// Смена статуса заказа (Выполняется) + /// + /// + /// public bool TakeOrderInWork(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выполняется); + return StatusUpdate(model, OrderStatus.Выполняется); } + + /// + /// Смена статуса заказа (Выдан) + /// + /// + /// public bool FinishOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Готов); + return StatusUpdate(model, OrderStatus.Выдан); } + + /// + /// Смена статуса заказа (Готов) + /// + /// + /// public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); + return StatusUpdate(model, OrderStatus.Готов); } + + /// + /// Проверка модели заказа + /// + /// + /// private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) @@ -106,19 +141,149 @@ namespace ComputersShopBusinessLogic.BusinessLogics { return; } - if (model.Sum <= 0) + if (model.ComputerId < 0) { - throw new ArgumentNullException("Цена должна быть больше 0", nameof(model.Sum)); + throw new ArgumentNullException("Некорректный идентификатор изделия", nameof(model.ComputerId)); } if (model.Count <= 0) { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); + throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); } - if (model.DateImplement != null && model.DateImplement < model.DateCreate) + if (model.Sum <= 0) { - throw new ArithmeticException("Дата завершения не может быть раньше даты начала"); + throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - _logger.LogInformation("Order. Id:{Id}. Sum:{Sum}. ComputerId:{ComputerId}", model.Id, model.Sum, model.ComputerId); + _logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. ComputerId: { ComputerId}", model.Id, model.Sum, model.ComputerId); + } + + /// + /// Смена статуса заказа + /// + /// + /// + /// + private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) + { + var element = _orderStorage.GetElement(new OrderSearchModel + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (element.Status + 1 != newStatus) + { + _logger.LogWarning("Change status operation failed"); + return false; + } + + model.Status = newStatus; + + if (newStatus == OrderStatus.Выдан) + { + var computer = _computerStorage.GetElement(new ComputerSearchModel { Id = element.ComputerId }); + if (computer == null) + { + _logger.LogWarning("Status change error. Computer not found"); + return false; + } + if (!CheckSupply(computer, element.Count)) + { + _logger.LogWarning("Status change error. Shop is overflowed"); + return false; + } + } + + if (model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = element.DateImplement; + } + CheckModel(model, false); + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Change status operation failed"); + return false; + } + return true; + } + + /// + /// Проверка заказа + /// + /// + /// + /// + public bool CheckSupply(IComputerModel model, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check supply operation error. Computers count < 0"); + return false; + } + + int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxComputers).Sum(); + int sumCount = _shopStorage.GetFullList().Select(x => x.ShopComputers.Select(y => y.Value.Item2).Sum()).Sum(); + int free = sumCapacity - sumCount; + if (free < count) + { + _logger.LogWarning("Check supply error. No place for new computers"); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + free = shop.MaxComputers; + foreach (var computer in shop.ShopComputers) + { + free -= computer.Value.Item2; + } + + if (free == 0) + { + continue; + } + + if (free >= count) + { + if (_shopLogic.AddComputerInShop(new() + { + Id = shop.Id + }, model, count)) + { + count = 0; + } + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + else + { + if (_shopLogic.AddComputerInShop(new() + { + Id = shop.Id + }, model, free)) + { + count -= free; + } + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; } } } diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs index 47bbef5..cf5f308 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs @@ -16,12 +16,28 @@ namespace ComputersShopBusinessLogic.BusinessLogics public class ShopLogic : IShopLogic { private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем магазинов + /// private readonly IShopStorage _shopStorage; + + /// + /// Конструктор + /// + /// + /// public ShopLogic(ILogger logger, IShopStorage shopStorage) { _logger = logger; _shopStorage = shopStorage; } + + /// + /// Получение списка + /// + /// + /// public List? ReadList(ShopSearchModel? model) { _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id); @@ -36,6 +52,13 @@ namespace ComputersShopBusinessLogic.BusinessLogics _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } + + /// + /// Получение отдельной записи + /// + /// + /// + /// public ShopViewModel? ReadElement(ShopSearchModel model) { if (model == null) @@ -55,6 +78,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } + + /// + /// Создание записи + /// + /// + /// public bool Create(ShopBindingModel model) { CheckModel(model); @@ -66,6 +95,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + + /// + /// Изменение записи + /// + /// + /// public bool Update(ShopBindingModel model) { CheckModel(model); @@ -77,6 +112,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + + /// + /// Удаление записи + /// + /// + /// public bool Delete(ShopBindingModel model) { CheckModel(model, false); @@ -89,6 +130,16 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + + /// + /// Добавление изделия в магазин + /// + /// + /// + /// + /// + /// + /// public bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count) { if (model == null) @@ -97,7 +148,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics } if (count <= 0) { - throw new ArgumentException("Кол-во изделий должно быть больше 0", nameof(count)); + throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count)); } _logger.LogInformation("AddComputerInShop. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); var element = _shopStorage.GetElement(model); @@ -108,6 +159,13 @@ namespace ComputersShopBusinessLogic.BusinessLogics } _logger.LogInformation("AddComputerInShop find. Id:{Id}", element.Id); + var countComputers = element.ShopComputers.Select(x => x.Value.Item2).Sum(); + if (element.MaxComputers - countComputers < count) + { + _logger.LogWarning("Shop is overflowed"); + return false; + } + if (element.ShopComputers.TryGetValue(computer.Id, out var pair)) { element.ShopComputers[computer.Id] = (computer, count + pair.Item2); @@ -125,10 +183,47 @@ namespace ComputersShopBusinessLogic.BusinessLogics Address = element.Address, ShopName = element.ShopName, DateOpening = element.DateOpening, - ShopComputers = element.ShopComputers + ShopComputers = element.ShopComputers, + MaxComputers = element.MaxComputers }); return true; } + + /// + /// Продажа изделий + /// + /// + /// + /// + /// + /// + public bool SellComputers(IComputerModel computer, int count) + { + if (computer == null) + { + throw new ArgumentNullException(nameof(computer)); + } + if (count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count)); + } + + if (_shopStorage.SellComputers(computer, count)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } + + /// + /// Проверка модели магазина + /// + /// + /// + /// + /// private void CheckModel(ShopBindingModel model, bool withParams = true) { if (model == null) diff --git a/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs index a284603..f3ede09 100644 --- a/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs +++ b/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs @@ -19,5 +19,6 @@ namespace ComputersShopContracts.BindingModels get; set; } = new(); + public int MaxComputers { get; set; } } } diff --git a/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IShopLogic.cs b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IShopLogic.cs index d17e847..e7aeda7 100644 --- a/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IShopLogic.cs @@ -18,5 +18,6 @@ namespace ComputersShopContracts.BusinessLogicsContracts bool Update(ShopBindingModel model); bool Delete(ShopBindingModel model); bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count); + bool SellComputers(IComputerModel computer, int count); } } diff --git a/ComputersShop/ComputersShopContracts/StoragesContracts/IOrderStorage.cs b/ComputersShop/ComputersShopContracts/StoragesContracts/IOrderStorage.cs index c986423..7b156ec 100644 --- a/ComputersShop/ComputersShopContracts/StoragesContracts/IOrderStorage.cs +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IOrderStorage.cs @@ -12,10 +12,40 @@ namespace ComputersShopContracts.StoragesContracts public interface IOrderStorage { List GetFullList(); - List GetFiltredList(OrderSearchModel model); + + /// + /// Получение фильтрованного списка + /// + /// + /// + 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/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs b/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs index 9d10aa7..0a27290 100644 --- a/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs @@ -7,6 +7,7 @@ using ComputersShopContracts.BindingModels; using ComputersShopContracts.SearchModels; using ComputersShopContracts.ViewModels; using ComputersShopDataModels; +using ComputersShopDataModels.Models; namespace ComputersShopContracts.StoragesContracts { @@ -18,5 +19,7 @@ namespace ComputersShopContracts.StoragesContracts ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model); + bool SellComputers(IComputerModel model, int count); + bool CheckCount(IComputerModel model, int count); } } diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs index 0dfb1e6..04150fc 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs @@ -23,5 +23,7 @@ namespace ComputersShopContracts.ViewModels get; set; } = new(); + [DisplayName("Максимальное количество изделий")] + public int MaxComputers { get; set; } } } diff --git a/ComputersShop/ComputersShopDataModels/Models/IShopModel.cs b/ComputersShop/ComputersShopDataModels/Models/IShopModel.cs index a76615d..d039166 100644 --- a/ComputersShop/ComputersShopDataModels/Models/IShopModel.cs +++ b/ComputersShop/ComputersShopDataModels/Models/IShopModel.cs @@ -12,5 +12,6 @@ namespace ComputersShopDataModels.Models string Address { get; } DateTime DateOpening { get; } Dictionary ShopComputers { get; } + int MaxComputers { get; } } } diff --git a/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs b/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs index ad0d7de..72d3979 100644 --- a/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs +++ b/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs @@ -11,35 +11,101 @@ namespace ComputersShopFileImplement { internal class DataFileSingleton { - private static DataFileSingleton? instance; - public readonly string ComponentFileName = "Component.xml"; - public readonly string OrderFileName = "Order.xml"; - public readonly string ComputerFileName = "Computer.xml"; - public List Components { get; private set; } - public List Orders { get; private set; } - public List Computers { get; private set; } - public static DataFileSingleton GetInstance() - { - if (instance == null) - { - instance = new DataFileSingleton(); - } - return instance; - } - public void SaveComponents() => SaveData(Components, ComponentFileName, - "Components", x => x.GetXElement); - public void SaveComputers() => SaveData(Computers, ComputerFileName, - "Computers", x => x.GetXElement); - public void SaveOrders() => SaveData(Orders, OrderFileName, - "Orders", x => x.GetXElement); + private static DataFileSingleton? _instance; + + /// + /// Название файла для хранения информации о компонентах + /// + private readonly string ComponentFileName = "Component.xml"; + + /// + /// Название файла для хранения информации о заказах + /// + private readonly string OrderFileName = "Order.xml"; + + /// + /// Название файла для хранения информации о изделиях + /// + private readonly string ComputerFileName = "Computer.xml"; + + /// + /// Название файла для хранения информации о магазинах + /// + private readonly string ShopFileName = "Shop.xml"; + + /// + /// Список классов-моделей компонентов + /// + public List Components { get; set; } + + /// + /// Список классов-моделей заказов + /// + public List Orders { get; set; } + + /// + /// Список классов-моделей изделий + /// + public List Computers { get; set; } + + /// + /// Список классов-моделей магазина + /// + public List Shops { get; set; } + + /// + /// Конструктор + /// private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Computers = LoadData(ComputerFileName, "Computer", x => Computer.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; } - private static List? LoadData(string filename, string xmlNodeName, - Func selectFunction) + + /// + /// Получить ссылку на класс + /// + /// + public static DataFileSingleton GetInstance() + { + if (_instance == null) + { + _instance = new DataFileSingleton(); + } + return _instance; + } + + /// + /// Сохранение компонентов + /// + public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); + + /// + /// Сохранение изделий + /// + public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement); + + /// + /// Сохранение заказов + /// + public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + + /// + /// Сохранение магазинов + /// + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + + /// + /// Метод для загрузки данных из xml-файла + /// + /// + /// + /// + /// + /// + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { @@ -47,8 +113,16 @@ namespace ComputersShopFileImplement } return new List(); } - private static void SaveData(List data, string filename, - string xmlNodeName, Func selectFunction) + + /// + /// Метод для сохранения данных в xml-файл + /// + /// + /// + /// + /// + /// + private static void SaveData(List data, string filename, string xmlNodeName, Func selectFunction) { if (data != null) { diff --git a/ComputersShop/ComputersShopFileImplement/Implements/OrderStorage.cs b/ComputersShop/ComputersShopFileImplement/Implements/OrderStorage.cs index 3317c1c..5e187e9 100644 --- a/ComputersShop/ComputersShopFileImplement/Implements/OrderStorage.cs +++ b/ComputersShop/ComputersShopFileImplement/Implements/OrderStorage.cs @@ -13,70 +13,129 @@ namespace ComputersShopFileImplement.Implements { public class OrderStorage : IOrderStorage { - private readonly DataFileSingleton source; + private readonly DataFileSingleton _source; + + /// + /// Конструктор + /// public OrderStorage() { - source = DataFileSingleton.GetInstance(); + _source = DataFileSingleton.GetInstance(); } + + /// + /// Получение полного списка + /// + /// public List GetFullList() { - return source.Orders.Select(x => GetViewModel(x)).ToList(); + return _source.Orders + .Select(x => GetViewModel(x)) + .ToList(); } - public List GetFiltredList(OrderSearchModel model) + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue) { return new(); } - return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList(); + + return _source.Orders + .Where(x => x.Id.Equals(model.Id)) + .Select(x => GetViewModel(x)) + .ToList(); } + + /// + /// Получение элемента + /// + /// + /// public OrderViewModel? GetElement(OrderSearchModel model) { if (!model.Id.HasValue) { return null; } - return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)); - } - public OrderViewModel? Update(OrderBindingModel model) - { - var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } - order.Update(model); - source.SaveOrders(); - return GetViewModel(order); + + return GetViewModel(_source.Orders + .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))); } + + /// + /// Добавление элемента + /// + /// + /// public OrderViewModel? Insert(OrderBindingModel model) { - model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; + model.Id = _source.Orders.Count > 0 ? _source.Orders.Max(x => x.Id) + 1 : 1; + var newOrder = Order.Create(model); if (newOrder == null) { return null; } - source.Orders.Add(newOrder); - source.SaveOrders(); + + _source.Orders.Add(newOrder); + _source.SaveOrders(); return GetViewModel(newOrder); } - public OrderViewModel? Delete(OrderBindingModel model) + + /// + /// Редактирование элемента + /// + /// + /// + public OrderViewModel? Update(OrderBindingModel model) { - var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); + var order = _source.Orders.FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; } - source.Orders.Remove(order); - source.SaveOrders(); + + order.Update(model); + _source.SaveOrders(); return GetViewModel(order); } + + /// + /// Удаление элемента + /// + /// + /// + public OrderViewModel? Delete(OrderBindingModel model) + { + var element = _source.Orders.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + _source.Orders.Remove(element); + _source.SaveOrders(); + return GetViewModel(element); + } + return null; + } + + /// + /// Получение модели заказа + /// + /// + /// private OrderViewModel GetViewModel(Order order) { var viewModel = order.GetViewModel; - var computer = source.Computers.FirstOrDefault(x => x.Id == order.ComputerId); - viewModel.ComputerName = computer?.ComputerName; + var computer = _source.Computers.FirstOrDefault(x => x.Id == order.ComputerId); + if (computer != null) + { + viewModel.ComputerName = computer.ComputerName; + } return viewModel; } } diff --git a/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs b/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..ebd3b0e --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,193 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels.Models; +using ComputersShopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + /// + /// Хранилище + /// + private readonly DataFileSingleton _source; + + /// + /// Конструктор + /// + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + return _source.Shops + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + + return _source.Shops + .Where(x => x.ShopName.Contains(model.ShopName)) + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение элемента + /// + /// + /// + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + + return _source.Shops + .FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && + x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; + + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + + _source.Shops.Add(newShop); + _source.SaveShops(); + return newShop.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public ShopViewModel? Update(ShopBindingModel model) + { + var shop = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + + shop.Update(model); + _source.SaveShops(); + return shop.GetViewModel; + } + + /// + /// Удаление элемента + /// + /// + /// + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + /// + /// Продажа изделий + /// + /// + /// + /// + public bool SellComputers(IComputerModel model, int count) + { + var computer = _source.Computers.FirstOrDefault(x => x.Id == model.Id); + if (computer == null || !CheckCount(model, count)) + { + return false; + } + + foreach (var shop in _source.Shops) + { + var computers = shop.ShopComputers; + foreach (var elem in computers.Where(x => x.Value.Item1.Id == computer.Id)) + { + var selling = Math.Min(elem.Value.Item2, count); + computers[elem.Value.Item1.Id] = (elem.Value.Item1, elem.Value.Item2 - selling); + count -= selling; + + if (count <= 0) + { + break; + } + } + + shop.Update(new ShopBindingModel + { + Id = model.Id, + ShopName = shop.ShopName, + Address = shop.Address, + DateOpening = shop.DateOpening, + ShopComputers = computers, + MaxComputers = shop.MaxComputers + }); + } + + _source.SaveShops(); + return true; + } + + /// + /// Проверка наличия в нужном количестве + /// + /// + /// + /// + public bool CheckCount(IComputerModel model, int count) + { + int store = _source.Shops + .Select(x => x.ShopComputers + .Select(y => (y.Value.Item1.Id == model.Id ? y.Value.Item2 : 0)) + .Sum()).Sum(); + return store >= count; + } + } +} diff --git a/ComputersShop/ComputersShopFileImplement/Models/Shop.cs b/ComputersShop/ComputersShopFileImplement/Models/Shop.cs new file mode 100644 index 0000000..a09d81f --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Models/Shop.cs @@ -0,0 +1,155 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace ComputersShopFileImplement.Models +{ + public class Shop : IShopModel + { + /// + /// Идентификатор + /// + public int Id { get; private set; } + + /// + /// Название магазина + /// + public string ShopName { get; private set; } = string.Empty; + + /// + /// Адрес магазина + /// + public string Address { get; private set; } = string.Empty; + + /// + /// Дата открытия магазина + /// + public DateTime DateOpening { get; private set; } + + /// + /// Коллекция изделий магазина в виде + /// «идентификатор изделия – количество изделий» + /// + public Dictionary Computers { get; private set; } = new(); + + /// + /// Коллекция изделий в магазине + /// + private Dictionary? _shopComputers = null; + public Dictionary ShopComputers + { + get + { + if (_shopComputers == null) + { + var source = DataFileSingleton.GetInstance(); + _shopComputers = Computers.ToDictionary(x => x.Key, y => ((source.Computers.FirstOrDefault(z => z.Id == y.Key) as IComputerModel)!, y.Value)); + } + return _shopComputers; + } + } + + /// + /// Максимальное количество изделий + /// + public int MaxComputers { get; private set; } + + /// + /// Создание модели магазина из данных файла + /// + /// + /// + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Address = element.Element("Address")!.Value, + DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), + Computers = element.Element("ShopComputers")!.Elements("ShopComputers")! + .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)), + MaxComputers = Convert.ToInt32(element.Element("MaxComputers")!.Value) + }; + } + + /// + /// Создание модели магазина + /// + /// + /// + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2), + MaxComputers = model.MaxComputers + }; + } + + /// + /// Изменение модели магазина + /// + /// + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2); + MaxComputers = model.MaxComputers; + _shopComputers = null; + } + + /// + /// Получение модели магазина + /// + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + ShopComputers = ShopComputers, + MaxComputers = MaxComputers + }; + + /// + /// Запись данных о модели магазина в файл + /// + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Address", Address), + new XElement("DateOpening", DateOpening.ToString()), + new XElement("ShopComputers", Computers.Select(x => + new XElement("ShopComputers", + new XElement("Key", x.Key), + new XElement("Value", x.Value))).ToArray()), + new XElement("MaxComputers", MaxComputers.ToString())); + } +} diff --git a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs index 834470f..3b494bf 100644 --- a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs +++ b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs @@ -11,10 +11,30 @@ namespace AbstractShopListImplement public class DataListSingleton { private static DataListSingleton? _instance; + + /// + /// Список классов-моделей компонентов + /// public List Components { get; set; } + + /// + /// Список классов-моделей заказов + /// public List Orders { get; set; } + + /// + /// Список классов-моделей изделий + /// public List Computers { get; set; } + + /// + /// Список классов-моделей магазинов + /// public List Shops { get; set; } + + /// + /// Конструктор + /// private DataListSingleton() { Components = new List(); @@ -22,6 +42,11 @@ namespace AbstractShopListImplement Computers = new List(); Shops = new List(); } + + /// + /// Получить ссылку на класс + /// + /// public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/ComputersShop/ComputersShopListImplement/Implements/OrderStorage.cs b/ComputersShop/ComputersShopListImplement/Implements/OrderStorage.cs index 56af78b..2b2be2d 100644 --- a/ComputersShop/ComputersShopListImplement/Implements/OrderStorage.cs +++ b/ComputersShop/ComputersShopListImplement/Implements/OrderStorage.cs @@ -15,50 +15,79 @@ namespace ComputersShopListImplement.Implements public class OrderStorage : IOrderStorage { private readonly DataListSingleton _source; + + /// + /// Конструктор + /// public OrderStorage() { _source = DataListSingleton.GetInstance(); } + + /// + /// Получение полного списка + /// + /// public List GetFullList() { var result = new List(); foreach (var order in _source.Orders) { - result.Add(AddComputerName(order.GetViewModel)); + result.Add(order.GetViewModel); } return result; } - public List GetFiltredList(OrderSearchModel model) + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(OrderSearchModel model) { var result = new List(); - if (model == null || !model.Id.HasValue) + if (!model.Id.HasValue) { return result; } + foreach (var order in _source.Orders) { if (order.Id == model.Id) { - result.Add(AddComputerName(order.GetViewModel)); + result.Add(order.GetViewModel); } } return result; } + + /// + /// Получение элемента + /// + /// + /// public OrderViewModel? GetElement(OrderSearchModel model) { if (!model.Id.HasValue) { return null; } + foreach (var order in _source.Orders) { if (model.Id.HasValue && order.Id == model.Id) { - return AddComputerName(order.GetViewModel); + return order.GetViewModel; } } return null; } + + /// + /// Добавление элемента + /// + /// + /// public OrderViewModel? Insert(OrderBindingModel model) { model.Id = 1; @@ -69,14 +98,22 @@ namespace ComputersShopListImplement.Implements model.Id = order.Id + 1; } } + var newOrder = Order.Create(model); if (newOrder == null) { return null; } + _source.Orders.Add(newOrder); - return AddComputerName(newOrder.GetViewModel); + return newOrder.GetViewModel; } + + /// + /// Редактирование элемента + /// + /// + /// public OrderViewModel? Update(OrderBindingModel model) { foreach (var order in _source.Orders) @@ -84,11 +121,17 @@ namespace ComputersShopListImplement.Implements if (order.Id == model.Id) { order.Update(model); - return AddComputerName(order.GetViewModel); + return order.GetViewModel; } } return null; } + + /// + /// Удаление элемента + /// + /// + /// public OrderViewModel? Delete(OrderBindingModel model) { for (int i = 0; i < _source.Orders.Count; ++i) @@ -97,20 +140,11 @@ namespace ComputersShopListImplement.Implements { var element = _source.Orders[i]; _source.Orders.RemoveAt(i); - return AddComputerName(element.GetViewModel); + return element.GetViewModel; } } return null; } - private OrderViewModel AddComputerName(OrderViewModel model) - { - var selectedComputer = _source.Computers.Find(computer => computer.Id == model.ComputerId); - if (selectedComputer != null) - { - model.ComputerName = selectedComputer.ComputerName; - } - return model; - } } } diff --git a/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs b/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs index 272a04c..8eaadc0 100644 --- a/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs +++ b/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs @@ -9,6 +9,7 @@ using ComputersShopContracts.SearchModels; using ComputersShopContracts.StoragesContracts; using ComputersShopContracts.ViewModels; using ComputersShopDataModels; +using ComputersShopDataModels.Models; using ComputersShopListImplement.Models; namespace ComputersShopListImplement.Implements @@ -16,10 +17,19 @@ namespace ComputersShopListImplement.Implements public class ShopStorage : IShopStorage { private readonly DataListSingleton _source; + + /// + /// Конструктор + /// public ShopStorage() { _source = DataListSingleton.GetInstance(); } + + /// + /// Получение полного списка + /// + /// public List GetFullList() { var result = new List(); @@ -29,6 +39,12 @@ namespace ComputersShopListImplement.Implements } return result; } + + /// + /// Получение фильтрованного списка + /// + /// + /// public List GetFilteredList(ShopSearchModel model) { var result = new List(); @@ -46,6 +62,12 @@ namespace ComputersShopListImplement.Implements } return result; } + + /// + /// Получение элемента + /// + /// + /// public ShopViewModel? GetElement(ShopSearchModel model) { if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) @@ -62,6 +84,12 @@ namespace ComputersShopListImplement.Implements } return null; } + + /// + /// Добавление элемента + /// + /// + /// public ShopViewModel? Insert(ShopBindingModel model) { model.Id = 1; @@ -82,6 +110,12 @@ namespace ComputersShopListImplement.Implements _source.Shops.Add(newShop); return newShop.GetViewModel; } + + /// + /// Редактирование элемента + /// + /// + /// public ShopViewModel? Update(ShopBindingModel model) { foreach (var shop in _source.Shops) @@ -94,6 +128,12 @@ namespace ComputersShopListImplement.Implements } return null; } + + /// + /// Удаление элемента + /// + /// + /// public ShopViewModel? Delete(ShopBindingModel model) { for (int i = 0; i < _source.Shops.Count; ++i) @@ -107,5 +147,29 @@ namespace ComputersShopListImplement.Implements } return null; } + + /// + /// Продажа изделий + /// + /// + /// + /// + /// + public bool SellComputers(IComputerModel model, int count) + { + throw new NotImplementedException(); + } + + /// + /// Проверка наличия в нужном количестве + /// + /// + /// + /// + /// + public bool CheckCount(IComputerModel model, int count) + { + throw new NotImplementedException(); + } } } diff --git a/ComputersShop/ComputersShopListImplement/Models/Shop.cs b/ComputersShop/ComputersShopListImplement/Models/Shop.cs index 7263885..44c0c7e 100644 --- a/ComputersShop/ComputersShopListImplement/Models/Shop.cs +++ b/ComputersShop/ComputersShopListImplement/Models/Shop.cs @@ -13,14 +13,41 @@ namespace ComputersShopListImplement.Models public class Shop : IShopModel { public int Id { get; private set; } + + /// + /// Название магазина + /// public string ShopName { get; private set; } = string.Empty; + + /// + /// Адрес магазина + /// public string Address { get; private set; } = string.Empty; + + /// + /// Дата открытия магазина + /// public DateTime DateOpening { get; private set; } + + /// + /// Коллекция изделий в магазине + /// public Dictionary ShopComputers { get; private set; } = new Dictionary(); + + /// + /// Максимальное количество изделий + /// + public int MaxComputers { get; private set; } + + /// + /// Создание модели магазина + /// + /// + /// public static Shop? Create(ShopBindingModel? model) { if (model == null) @@ -34,9 +61,15 @@ namespace ComputersShopListImplement.Models ShopName = model.ShopName, Address = model.Address, DateOpening = model.DateOpening, - ShopComputers = model.ShopComputers + ShopComputers = model.ShopComputers, + MaxComputers = model.MaxComputers }; } + + /// + /// Изменение модели магазина + /// + /// public void Update(ShopBindingModel? model) { if (model == null) @@ -48,14 +81,20 @@ namespace ComputersShopListImplement.Models Address = model.Address; DateOpening = model.DateOpening; ShopComputers = model.ShopComputers; + MaxComputers = model.MaxComputers; } + + /// + /// Получение модели магазина + /// public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpening = DateOpening, - ShopComputers = ShopComputers + ShopComputers = ShopComputers, + MaxComputers = MaxComputers }; } } diff --git a/ComputersShop/ComputersShopView/FormMain.Designer.cs b/ComputersShop/ComputersShopView/FormMain.Designer.cs index 3511353..a6f14b8 100644 --- a/ComputersShop/ComputersShopView/FormMain.Designer.cs +++ b/ComputersShop/ComputersShopView/FormMain.Designer.cs @@ -40,6 +40,7 @@ this.buttonOrderReady = new System.Windows.Forms.Button(); this.buttonIssuedOrder = new System.Windows.Forms.Button(); this.buttonRef = new System.Windows.Forms.Button(); + this.продажаИзделийToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -61,7 +62,8 @@ this.компонентыToolStripMenuItem, this.изделияToolStripMenuItem, this.магазиныToolStripMenuItem, - this.поставкиToolStripMenuItem}); + this.поставкиToolStripMenuItem, + this.продажаИзделийToolStripMenuItem}); this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24); this.справочникиToolStripMenuItem.Text = "Справочники"; @@ -157,6 +159,12 @@ this.buttonRef.UseVisualStyleBackColor = true; this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); // + // продажаИзделийToolStripMenuItem + // + this.продажаИзделийToolStripMenuItem.Name = "продажаИзделийToolStripMenuItem"; + this.продажаИзделийToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.продажаИзделийToolStripMenuItem.Text = "Продажа изделий"; + // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); @@ -195,5 +203,6 @@ private ToolStripMenuItem изделияToolStripMenuItem; private ToolStripMenuItem магазиныToolStripMenuItem; private ToolStripMenuItem поставкиToolStripMenuItem; + private ToolStripMenuItem продажаИзделийToolStripMenuItem; } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopView/FormMain.cs b/ComputersShop/ComputersShopView/FormMain.cs index f9ed2e6..bf14e37 100644 --- a/ComputersShop/ComputersShopView/FormMain.cs +++ b/ComputersShop/ComputersShopView/FormMain.cs @@ -80,6 +80,15 @@ namespace ComputersShopView form.ShowDialog(); } } + private void ПродажаизделийToolStripMenuItem_Click(object sender, EventArgs + e) + { + var services = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (services is FormSell form) + { + form.ShowDialog(); + } + } private void ButtonCreateOrder_Click(object sender, EventArgs e) { var service = diff --git a/ComputersShop/ComputersShopView/FormSell.Designer.cs b/ComputersShop/ComputersShopView/FormSell.Designer.cs new file mode 100644 index 0000000..052f8bc --- /dev/null +++ b/ComputersShop/ComputersShopView/FormSell.Designer.cs @@ -0,0 +1,120 @@ +namespace ComputersShopView +{ + partial class FormSell + { + /// + /// 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.labelComputer = new System.Windows.Forms.Label(); + this.labelCount = new System.Windows.Forms.Label(); + this.comboBoxComputer = 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(); + // + // labelComputer + // + this.labelComputer.AutoSize = true; + this.labelComputer.Location = new System.Drawing.Point(12, 50); + this.labelComputer.Name = "labelComputer"; + this.labelComputer.Size = new System.Drawing.Size(71, 20); + this.labelComputer.TabIndex = 0; + this.labelComputer.Text = "Изделие:"; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(12, 106); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(93, 20); + this.labelCount.TabIndex = 1; + this.labelCount.Text = "Количество:"; + // + // comboBoxComputer + // + this.comboBoxComputer.FormattingEnabled = true; + this.comboBoxComputer.Location = new System.Drawing.Point(137, 42); + this.comboBoxComputer.Name = "comboBoxComputer"; + this.comboBoxComputer.Size = new System.Drawing.Size(267, 28); + this.comboBoxComputer.TabIndex = 2; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(137, 99); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(267, 27); + this.textBoxCount.TabIndex = 3; + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(244, 154); + 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(368, 154); + 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); + // + // FormSell + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(474, 199); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.comboBoxComputer); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.labelComputer); + this.Name = "FormSell"; + this.Text = "Продажа"; + this.Load += new System.EventHandler(this.FormSell_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelComputer; + private Label labelCount; + private ComboBox comboBoxComputer; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopView/FormSell.cs b/ComputersShop/ComputersShopView/FormSell.cs new file mode 100644 index 0000000..5de3f68 --- /dev/null +++ b/ComputersShop/ComputersShopView/FormSell.cs @@ -0,0 +1,107 @@ +using ComputersShopContracts.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 ComputersShopView +{ + public partial class FormSell : Form + { + private readonly ILogger _logger; + + /// + /// Бизнес-логика для изделий + /// + private readonly IComputerLogic _logicC; + + /// + /// Бизнес-логика для магазинов + /// + private readonly IShopLogic _logicS; + public FormSell(ILogger logger, IComputerLogic planeLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _logger = logger; + _logicC = planeLogic; + _logicS = shopLogic; + } + private void FormSell_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий для продажи"); + try + { + var list = _logicC.ReadList(null); + if (list != null) + { + comboBoxComputer.DisplayMember = "ComputerName"; + comboBoxComputer.ValueMember = "Id"; + comboBoxComputer.DataSource = list; + comboBoxComputer.SelectedItem = null; + } + } + 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(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxComputer.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Продажа изделий"); + _logger.LogInformation("Создание заказа"); + try + { + var operationResult = _logicS.SellComputers( + _logicC.ReadElement(new() { Id = Convert.ToInt32(comboBoxComputer.SelectedValue) }), + Convert.ToInt32(textBoxCount.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(); + } + } +} diff --git a/ComputersShop/ComputersShopView/FormSell.resx b/ComputersShop/ComputersShopView/FormSell.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/ComputersShop/ComputersShopView/FormSell.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/ComputersShop/ComputersShopView/FormShop.Designer.cs b/ComputersShop/ComputersShopView/FormShop.Designer.cs index a1c7aa7..342d030 100644 --- a/ComputersShop/ComputersShopView/FormShop.Designer.cs +++ b/ComputersShop/ComputersShopView/FormShop.Designer.cs @@ -35,11 +35,13 @@ this.textBoxAddress = new System.Windows.Forms.TextBox(); this.textBoxName = new System.Windows.Forms.TextBox(); this.dataGridViewShop = new System.Windows.Forms.DataGridView(); - this.buttonSave = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ComputerName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.buttonSave = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.labelMaxComputers = new System.Windows.Forms.Label(); + this.textBoxMaxComputers = new System.Windows.Forms.TextBox(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewShop)).BeginInit(); this.SuspendLayout(); // @@ -72,24 +74,24 @@ // // dateTimePicker // - this.dateTimePicker.Location = new System.Drawing.Point(104, 97); + this.dateTimePicker.Location = new System.Drawing.Point(121, 97); this.dateTimePicker.Name = "dateTimePicker"; - this.dateTimePicker.Size = new System.Drawing.Size(403, 27); + this.dateTimePicker.Size = new System.Drawing.Size(386, 27); this.dateTimePicker.TabIndex = 3; // // textBoxAddress // - this.textBoxAddress.Location = new System.Drawing.Point(104, 61); + this.textBoxAddress.Location = new System.Drawing.Point(121, 61); this.textBoxAddress.Name = "textBoxAddress"; - this.textBoxAddress.Size = new System.Drawing.Size(403, 27); + this.textBoxAddress.Size = new System.Drawing.Size(386, 27); this.textBoxAddress.TabIndex = 4; this.textBoxAddress.TextChanged += new System.EventHandler(this.FormShop_Load); // // textBoxName // - this.textBoxName.Location = new System.Drawing.Point(104, 22); + this.textBoxName.Location = new System.Drawing.Point(121, 22); this.textBoxName.Name = "textBoxName"; - this.textBoxName.Size = new System.Drawing.Size(403, 27); + this.textBoxName.Size = new System.Drawing.Size(386, 27); this.textBoxName.TabIndex = 5; // // dataGridViewShop @@ -99,33 +101,13 @@ this.id, this.ComputerName, this.Count}); - this.dataGridViewShop.Location = new System.Drawing.Point(23, 156); + this.dataGridViewShop.Location = new System.Drawing.Point(23, 197); this.dataGridViewShop.Name = "dataGridViewShop"; this.dataGridViewShop.RowHeadersWidth = 51; this.dataGridViewShop.RowTemplate.Height = 29; this.dataGridViewShop.Size = new System.Drawing.Size(507, 173); this.dataGridViewShop.TabIndex = 6; // - // buttonSave - // - this.buttonSave.Location = new System.Drawing.Point(319, 354); - this.buttonSave.Name = "buttonSave"; - this.buttonSave.Size = new System.Drawing.Size(94, 29); - this.buttonSave.TabIndex = 7; - this.buttonSave.Text = "Сохранить"; - this.buttonSave.UseVisualStyleBackColor = true; - this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); - // - // buttonCancel - // - this.buttonCancel.Location = new System.Drawing.Point(436, 354); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(94, 29); - this.buttonCancel.TabIndex = 8; - this.buttonCancel.Text = "Отмена"; - this.buttonCancel.UseVisualStyleBackColor = true; - this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); - // // id // this.id.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; @@ -148,11 +130,49 @@ this.Count.MinimumWidth = 6; this.Count.Name = "Count"; // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(319, 376); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(94, 29); + this.buttonSave.TabIndex = 7; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(436, 376); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(94, 29); + this.buttonCancel.TabIndex = 8; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // labelMaxComputers + // + this.labelMaxComputers.AutoSize = true; + this.labelMaxComputers.Location = new System.Drawing.Point(12, 150); + this.labelMaxComputers.Name = "labelMaxComputers"; + this.labelMaxComputers.Size = new System.Drawing.Size(103, 20); + this.labelMaxComputers.TabIndex = 9; + this.labelMaxComputers.Text = "Вместимость:"; + // + // textBoxMaxComputers + // + this.textBoxMaxComputers.Location = new System.Drawing.Point(121, 147); + this.textBoxMaxComputers.Name = "textBoxMaxComputers"; + this.textBoxMaxComputers.Size = new System.Drawing.Size(386, 27); + this.textBoxMaxComputers.TabIndex = 10; + // // FormShop // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(546, 395); + this.ClientSize = new System.Drawing.Size(546, 417); + this.Controls.Add(this.textBoxMaxComputers); + this.Controls.Add(this.labelMaxComputers); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonSave); this.Controls.Add(this.dataGridViewShop); @@ -185,5 +205,7 @@ private DataGridViewTextBoxColumn id; private DataGridViewTextBoxColumn ComputerName; private DataGridViewTextBoxColumn Count; + private Label labelMaxComputers; + private TextBox textBoxMaxComputers; } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopView/FormShop.cs b/ComputersShop/ComputersShopView/FormShop.cs index 1cec395..272fa46 100644 --- a/ComputersShop/ComputersShopView/FormShop.cs +++ b/ComputersShop/ComputersShopView/FormShop.cs @@ -43,6 +43,7 @@ namespace ComputersShopView textBoxName.Text = view.ShopName; textBoxAddress.Text = view.Address; dateTimePicker.Text = view.DateOpening.ToString(); + textBoxMaxComputers.Text = view.MaxComputers.ToString(); _shopComputers = view.ShopComputers ?? new Dictionary(); LoadData(); } @@ -108,7 +109,8 @@ namespace ComputersShopView ShopName = textBoxName.Text, Address = textBoxAddress.Text, DateOpening = dateTimePicker.Value.Date, - ShopComputers = _shopComputers + ShopComputers = _shopComputers, + MaxComputers = Convert.ToInt32(textBoxMaxComputers.Text) }; var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); if (!operationResult) diff --git a/ComputersShop/ComputersShopView/FormSupply.Designer.cs b/ComputersShop/ComputersShopView/FormSupply.Designer.cs index 220fd24..74d893d 100644 --- a/ComputersShop/ComputersShopView/FormSupply.Designer.cs +++ b/ComputersShop/ComputersShopView/FormSupply.Designer.cs @@ -105,6 +105,11 @@ // numericUpDownCount // this.numericUpDownCount.Location = new System.Drawing.Point(142, 139); + this.numericUpDownCount.Maximum = new decimal(new int[] { + 1000, + 0, + 0, + 0}); this.numericUpDownCount.Name = "numericUpDownCount"; this.numericUpDownCount.Size = new System.Drawing.Size(348, 27); this.numericUpDownCount.TabIndex = 8; diff --git a/ComputersShop/ComputersShopView/FormSupply.cs b/ComputersShop/ComputersShopView/FormSupply.cs index 5c58220..cbd8e91 100644 --- a/ComputersShop/ComputersShopView/FormSupply.cs +++ b/ComputersShop/ComputersShopView/FormSupply.cs @@ -50,6 +50,7 @@ namespace ComputersShopView _logger.LogError(ex, "Ошибка загрузки списка магазинов"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } + _logger.LogInformation("Загрузка изделий"); try { diff --git a/ComputersShop/ComputersShopView/Program.cs b/ComputersShop/ComputersShopView/Program.cs index bcdd41f..c0d885b 100644 --- a/ComputersShop/ComputersShopView/Program.cs +++ b/ComputersShop/ComputersShopView/Program.cs @@ -67,6 +67,7 @@ namespace ComputersShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file